ReactEasy
Build a counter app
A counter app holds a number in state with useState and updates it from buttons using functional updates. A good interview version adds a configurable step, limits (min and max), reset, and accessible labels, and keeps derived values like "at limit" computed during render.
Requirements to cover
- Show the current count.
- Increment and decrement buttons.
- Reset to the initial value.
- Optional step input and bounds.
- Disable buttons at the limits.
Key points to talk through
- Functional updates (
setCount((c) => c + step)) avoid stale values when clicks happen quickly. - Clamping with
Math.min/Math.maxkeeps the count in range. - Derived state:
atMinandatMaxare computed, not stored. - Controlled number input for the step, with validation (
Number.isFinite, minimum of 1). - Accessibility: buttons have
aria-labels, the count is announced witharia-live="polite". - Extensions: persist to
localStorage, keyboard shortcuts (arrow keys), or auseCountercustom hook that returns{ count, increment, decrement, reset }for reuse and testing.
Testing
Render it, click increment twice with user-event, assert the displayed value, and check that the decrement button is disabled at the minimum.
Code example
tsx
1import { useState } from "react";23type Props = { initial?: number; min?: number; max?: number };45export function Counter({ initial = 0, min = -Infinity, max = Infinity }: Props) {6 const [count, setCount] = useState(initial);7 const [step, setStep] = useState(1);89 const clamp = (n: number) => Math.min(max, Math.max(min, n));10 const atMin = count <= min; // derived, not stored11 const atMax = count >= max;1213 return (14 <section aria-label="Counter">15 <p aria-live="polite" style={{ fontSize: 32 }}>{count}</p>1617 <button aria-label="Decrement" disabled={atMin} onClick={() => setCount((c) => clamp(c - step))}>−</button>18 <button aria-label="Increment" disabled={atMax} onClick={() => setCount((c) => clamp(c + step))}>+</button>19 <button onClick={() => setCount(initial)}>Reset</button>2021 <label>22 Step{" "}23 <input24 type="number"25 min={1}26 value={step}27 onChange={(e) => {28 const n = Number(e.target.value);29 setStep(Number.isFinite(n) && n >= 1 ? n : 1);30 }}31 />32 </label>33 </section>34 );35}3637// <Counter initial={0} min={0} max={10} />
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.