Start the interval in useEffect and return a cleanup that clears it. Without one, every remount adds another interval, and in development <StrictMode> mounts effects twice, so the callback fires twice per tick. Keep the latest callback in a useRef updated after each render, and let the interval call saved.current(). Then the effect depends only on delay, so re-renders don't restart the timer and the callback never reads stale state. Putting the callback in state would re-render for nothing, and putting it in the deps restarts the timer on every render. delay === null is a clean way to pause.
Implement a custom React hook that uses setInterval. Common gotcha: the interval double-fires unless you keep the callback in a useRef instead of useState.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
A ticking counter: setInterval in an effect, clearInterval in its cleanup, and the updater form setCount((c) => c + 1) so the callback never reads an old count. The last two checks show both classic bugs: no cleanup double-fires under Strict Mode, and setCount(count + 1) in a [] effect is stuck at 1. The checks run on a small hook harness that follows React's rules, not on React itself.
// import { useEffect, useState } from 'react';// A counter that goes up once every `delay` ms.function useTicker(delay) {const [count, setCount] = useState(0);useEffect(() => {// The updater form reads the current count, so this closure never goes stale.const id = setInterval(() => setCount((c) => c + 1), delay);// Without cleanup, every remount (and Strict Mode's extra mount) leaves another interval running.return () => clearInterval(id);}, [delay]);return count;}
passes 5 checks run on every build, against the native method where there is one
- ticks once per delay
- Strict Mode's double mount still leaves one interval
- unmount clears the interval
- the gotcha: without cleanup, Strict Mode double-fires
- the other gotcha: reading count in a [] effect gets stuck at 1
A generic useInterval(callback, delay) gets a new callback function on every render. With the callback in the deps, each render clears and restarts the timer, and a component that re-renders more often than delay never fires at all (a check proves it). Instead, store the callback in a ref after each render and have the interval call saved.current(). A ref is right because changing it shouldn't re-render. The timer's effect then depends only on delay.
// import { useEffect, useRef } from 'react';// Call `callback` every `delay` ms, always the latest callback, without restarting the timer// when the component re-renders.function useInterval(callback, delay) {const saved = useRef(callback);// Remember the newest callback after every render. A ref, not state: changing it must not// re-render, and the interval reads it when it fires.useEffect(() => {saved.current = callback;});// The timer depends only on the delay.useEffect(() => {const id = setInterval(() => saved.current(), delay);return () => clearInterval(id);}, [delay]);}
passes 5 checks run on every build, against the native method where there is one
- calls the latest callback
- re-rendering doesn't restart the timer
- why: with the callback in the deps, frequent renders mean it never fires
- a new delay restarts the timer
- one interval under Strict Mode, none after unmount
Passing null as the delay pauses without a separate flag: the effect sets no timer. A countdown built on top stops itself by passing null once it reaches zero. It computes the remaining time from Date.now() instead of counting ticks, because intervals fire late when the main thread is busy and browsers throttle timers in background tabs. React 19.2 also has useEffectEvent, which can replace the ref: an effect event always sees the latest props and state without being an effect dependency.
// import { useEffect, useRef, useState } from 'react';function useInterval(callback, delay) {const saved = useRef(callback);useEffect(() => {saved.current = callback;});useEffect(() => {if (delay === null) return; // null pauses: no timer at allconst id = setInterval(() => saved.current(), delay);return () => clearInterval(id);}, [delay]);}// A countdown built on it. Remaining time comes from the clock, not from counting ticks:// intervals fire late (busy main thread, background tabs), so counting ticks drifts.function useCountdown(ms, step = 1000) {const [end] = useState(() => Date.now() + ms);const [left, setLeft] = useState(ms);useInterval(() => setLeft(Math.max(0, end - Date.now())), left > 0 ? step : null);return left;}
passes 3 checks run on every build, against the native method where there is one
- null pauses, a number resumes
- countdown reaches zero and stops its timer
- countdown with an uneven step never goes below zero
Strict Mode runs effects twice in development
React mounts, unmounts and mounts every component again in development under <StrictMode>, precisely to expose effects that forget to clean up, like an interval that never gets cleared.
Effect events
React's docs use the same problem, a timer or connection that shouldn't restart when a callback changes, to introduce useEffectEvent.
Background tabs throttle timers
Browsers limit timers in inactive tabs to once a second or less often, which is why a countdown should read the clock rather than count ticks.
No cleanup: intervals pile up on remount and double-fire under Strict Mode.
setCount(count + 1)inside a[]effect: the closure keeps the firstcountforever.The callback in the effect's deps: the timer restarts every render and may never fire.
Storing the callback in
useState: it re-renders for nothing and still needs the effect to read it.Counting ticks for elapsed time: intervals drift and are throttled in background tabs.
Why update the ref in an effect and not during render?
React's rules say not to write refs during rendering: a render can be thrown away (concurrent rendering, Strict Mode's double render), and then the ref would point at a callback from a render that never committed.
How would you write useTimeout?
Same shape with setTimeout/clearTimeout: latest callback in a ref, effect keyed on delay, null to cancel. Often it also returns a reset function.
When is setInterval the wrong tool for animation?
For anything drawn every frame. requestAnimationFrame syncs with the display's refresh and pauses in background tabs.
- react.dev/reference/react/useEffect#connecting-to-an-external-system
- react.dev/reference/react/useRef#referencing-a-value-with-a-ref
- react.dev/reference/react/StrictMode
- react.dev/reference/react/useEffectEvent
- overreacted.io/making-setinterval-declarative-with-react-hooks/
- developer.mozilla.org/en-US/docs/Web/API/Window/setInterval