← JavaScript Coding

React Hook: useTimeout

medium

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 delay is a number.
  • Do nothing when delay is null.
  • 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.

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.

  • 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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

4. Improve a function

JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub