React Hook: useTimeout
Problem statement
Implement useTimeout(callback, delay), a React hook that runs a callback after a delay.
The important part is lifecycle control: keep the latest callback available, restart the timer only when the delay changes, and clean up the timer when the component unmounts.
Requirements
- Store the latest callback in a ref so the timer does not need to restart on every callback identity change.
- Start a timeout when
delayis a number. - Do nothing when
delayisnull. - Return cleanup from the timer effect so React can clear the timeout.
How to approach React Hook: useTimeout
The strategy an interviewer expects you to reach for.
useTimeout is the React version of cancellable timeout: schedule on mount/delay change, clear on unmount, and never call a stale callback. Naive move One effect that closes over callback. When the parent re-renders with a new callback, the timer still sees the old one — or you reset the timer too often. Where it breaks Stale closures and missing cleanup. delay === null should pause. Changing callback should not restart the timer; changing delay should. The fix Ref for the latest callback (effect #1). Effect #2 depends on delay, sets the timer, and clears on cleanup / null delay. Remember: Callback in a ref; timer effect keyed by delay only. Say this in the interview: I'd keep the latest callback in a ref and put setTimeout/clearTimeout in an effect that only re-runs when delay changes.
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.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.