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

  1. Show the current count.
  2. Increment and decrement buttons.
  3. Reset to the initial value.
  4. Optional step input and bounds.
  5. 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.max keeps the count in range.
  • Derived state: atMin and atMax are 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 with aria-live="polite".
  • Extensions: persist to localStorage, keyboard shortcuts (arrow keys), or a useCounter custom 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";
2
3type Props = { initial?: number; min?: number; max?: number };
4
5export function Counter({ initial = 0, min = -Infinity, max = Infinity }: Props) {
6 const [count, setCount] = useState(initial);
7 const [step, setStep] = useState(1);
8
9 const clamp = (n: number) => Math.min(max, Math.max(min, n));
10 const atMin = count <= min; // derived, not stored
11 const atMax = count >= max;
12
13 return (
14 <section aria-label="Counter">
15 <p aria-live="polite" style={{ fontSize: 32 }}>{count}</p>
16
17 <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>
20
21 <label>
22 Step{" "}
23 <input
24 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}
36
37// <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.

Open in study app