DOM & Browsereasy
Build a Counter React component
Implement a `Counter` component: show the current count, buttons to increment and decrement, and a reset button. The count must never go below zero. Use idiomatic React (functional component + hooks).
Asked at Meta, Airbnb, Stripe
Answer
function Counter() { const [count, setCount] = React.useState(0) return ( <section aria-label="Counter"> <p>Count: {count}</p> <button type="button" onClick={() => setCount((c) => c + 1)}> + </button> <button type="button" onClick={() => setCount((c) => Math.max(0, c - 1))} > − </button> <button type="button" onClick={() => setCount(0)}> Reset </button> </section> ) } // Interview talking points: // - Functional updates avoid stale closures when multiple updates batch. // - Math.max(0, c - 1) encodes the business rule in one place. // - Prefer type="button" inside forms so you do not accidentally submit.
Source: common React screen interview