useCounterLoading saved progress…

useCounter

Build a custom React hook that manages a single number. useCounter is the "hello world" of custom hooks: it wraps useState and hands back the current count plus three helpers — increment, decrement, and reset. The point isn't the arithmetic; it's learning how a hook bundles state together with the functions that change it into one tidy, reusable package a component can drop in with a single line.

Signature

function useCounter(initialValue?: number): {
  count: number;
  increment: () => void;
  decrement: () => void;
  reset: () => void;
};

initialValue defaults to 0 when omitted. reset always returns the count to that original initialValue, not to 0.

Examples

function Stepper() {
  const { count, increment, decrement, reset } = useCounter(10);

  return (
    <div>
      <span>{count}</span>
      <button onClick={increment}>+</button>
      <button onClick={decrement}></button>
      <button onClick={reset}>reset</button>
    </div>
  );
}
// renders 10; + → 11; − → 9; reset → back to 10
// Calling a setter several times in one event should accumulate.
// Three increments from 0 must land on 3, not on 1.
increment();
increment();
increment();
// count === 3

Notes

  • The count may go negative. decrement has no lower bound — from 0 it yields -1. Clamping is out of scope here.
  • reset targets the initial value. If the hook was created with useCounter(7), reset restores 7.
  • Helpers must survive batched updates. React groups several setter calls in one event into a single re-render, so updates have to be expressed in a way that stacks correctly rather than colliding.
  • You don't need to memoize the helpers for this version — returning fresh functions each render is acceptable. Stabilizing their identity is a separate exercise.
Loading editor…