Sub topic 15
The latest-callback pattern
This chapter assumes you know useState, useEffect with a dependency array, closures, and that ref.current can be changed without causing a re-render.
The problem: stale closures in long-lived callbacks
A callback passed to setInterval or an event listener captures the variables from the render in which it was created. If the interval is set up once, it keeps calling that first version of the callback, and the callback keeps seeing old props and state.
The obvious fix is to put the callback in the effect's dependency array. Then the interval is cleared and recreated every time the callback changes. If the callback is a new function on every render, which is the normal case, the timer restarts on every render. A timer that restarts often may never fire.
You want two things at once:
- The timer is created only when its delay changes.
- Each tick runs the newest callback.
The pattern
Keep the callback in a ref. Update the ref after each render. Let the long-lived function read ref.current when it runs.
import { useEffect, useRef } from 'react';
export function useInterval(callback, delay) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
if (delay === null) return;
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
}The hook has two effects with different jobs:
- The first effect has no dependency array, so it runs after every render and stores the newest
callbackin the ref. - The second effect depends only on
delay. It creates the interval once per delay value. The function it passes tosetIntervalis a small wrapper that readssavedCallback.currentat tick time, so it always calls the latest callback.
The ref works here because changing it does not need to update the screen. It is plumbing between renders and a long-lived function.
Using it
import { useState } from 'react';
import { useInterval } from './useInterval';
export function Ticker() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
useInterval(() => {
setCount((c) => c + step);
}, 1000);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setStep((s) => s + 1)}>Step: {step}</button>
</div>
);
}When you click the button, step changes and the component re-renders with a new callback. The interval is not recreated, so the one-second rhythm is not disturbed. The next tick uses the new step. Passing null as the delay pauses the timer.
Common mistakes
- Writing the ref during render. Do not write
savedCallback.current = callbackin the component body. Render must stay pure, and a render that React discards would leave the ref holding a callback that never committed. Update it in an effect. - Putting the callback in the interval effect's dependencies. This brings back the restart problem.
- Using it where state is needed. If the value must appear on screen, keep it in state. This pattern is for values that only a long-lived function reads.
Exercise
In useInterval, why does the first effect have no dependency array, and why is the callback absent from the second effect's dependencies?
Show answer
The first effect must run after every render so the ref always holds the newest callback. The second effect reads the callback through the ref at tick time, so it does not depend on the callback. Its only dependency is delay, which means the interval is recreated only when the delay changes.