useCounter II
easyreacthooksstate
Asked at



Airbnb, Atlassian, Meta, Microsoft, Swiggy
Problem statement
Implement an optimized version of the useCounter hook. The returned methods should be memoized so the same function instance is returned across re-renders.
Usage
export default function Component() {
const { count, increment, decrement, reset, setCount } = useCounter();
return (
<div>
<p>Counter: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}
Arguments
initialValue: initial counter value. Defaults to0.
Return Value
count: current counter value.increment(): increment by one.decrement(): decrement by one.reset(): reset to the initial value.setCount(value): set the counter value directly.
increment, decrement, reset, and setCount must be stable function instances across re-renders.
Requirements & constraints
- Use React hooks.
- Returned method identities should remain stable across re-renders.
- Default initial value is 0.
How to approach useCounter II
The strategy an interviewer expects you to reach for.
Approach The state itself lives in useState. The returned methods are wrapped in useCallback with empty dependency arrays so their identity stays stable across re-renders.
Premium
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Live React sandbox pre-wired for this component
- Time-boxed checkpoints that mirror a real 45-minute round
- Interviewer scoring criteria and a full reference implementation
Already a member? Log in to open the workspace.