useCounter Hook

EasyReact Hooks15 min6 tests

Build a useCounter custom hook that manages a numeric counter with increment, decrement, and reset actions, then wire it into a small UI.

Implement a custom React hook useCounter(initial = 0) that encapsulates counter state and returns { count, increment, decrement, reset }.

  • count is the current numeric value (starts at initial).
  • increment() adds 1 to the count.
  • decrement() subtracts 1 from the count (it may go negative).
  • reset() returns the count back to the original initial value.

The App component must use this hook to drive a tiny UI:

  • A live region (role="status") that always displays the current count.
  • An Increment button, a Decrement button, and a Reset button.

The starter renders the shell and stubs the hook so the buttons do nothing — your job is to implement the hook so all the buttons work and the displayed count stays in sync.

Requirements

  • Implement useCounter(initial = 0) inside App.tsx returning an object { count, increment, decrement, reset }.
  • increment() increases the count by 1; decrement() decreases it by 1 (negatives allowed).
  • reset() sets the count back to the initial value passed to the hook.
  • Display the current count in an element with role="status".
  • Provide accessible Increment, Decrement, and Reset buttons that update the displayed count.
  • Use only React (useState/useCallback) and inline styles — no external libraries, no timers.
Hints (4)
  1. Use useState(initial) inside the hook to hold the count; return the value plus updater functions.
  2. Prefer the functional updater form, e.g. setCount(c => c + 1), so rapid clicks stay correct.
  3. Capture the initial value so reset() can restore it — setCount(initial) works since initial is a stable prop/argument.
  4. In App, render the count inside <div role="status"> and call the hook's functions from each button's onClick.

Topics

  • React
  • React Hooks

Asked at

PharmEasy · Myntra · Groww · Paytm · Razorpay · Flipkart

Join Us
blur