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.
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.
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
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.