Sub topic 15
The latest-callback pattern
This chapter covers one use of useRef: keeping the newest version of a callback or value available inside a long-lived effect, without restarting that effect each time the value changes.
It assumes you know JavaScript closures, function components and JSX, useState, and basic useEffect setup and cleanup. You should also know the rule from earlier chapters: don't read or write ref.current during rendering.
The problem: stale closures in long-lived effects
A closure captures the variables that were in scope when a function was created. Every render creates new functions with new captured values. An effect that sets up a timer, a subscription, or an event listener creates a function once and keeps it for as long as the effect stays active. That function sees only the values from the render that created it.
Here is a counter that tries to log its own value every second:
import { useEffect, useState } from 'react';
export function BrokenLogger() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
console.log('count is', count);
}, 1000);
return () => clearInterval(id);
}, []);
return <button onClick={() => setCount(count + 1)}>Clicked {count}</button>;
}The effect runs once, on mount, because its dependency array is empty. The interval callback closes over count from that first render, which is 0. After ten clicks the button shows 10, but the console still prints count is 0. This is a stale closure.
Two obvious fixes and their costs
You have two ordinary options, and both have a cost.
- Add
countto the dependency array. The log is now correct, but the effect tears down and recreates the interval on every change. Ifcountchanges more often than the interval fires, the timer may never fire at all, because it is reset before its delay elapses. - Use a functional state update such as
setSeconds((s) => s + 1). This works when you only need to update state from the previous value. It does not help when the callback needs to read the current value for other work, such as logging, calling a prop, or sending a request.
The latest-callback pattern is a third option. It keeps the effect stable and still gives it access to current values.
The pattern
Store the callback in a ref. Update the ref after each render. Have the long-lived function call ref.current at the moment it runs, instead of capturing the callback directly.
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]);
}This hook has two effects, and each has one job.
- The first effect has no dependency array, so it runs after every render. It copies the newest
callbackintosavedCallback.current. - The second effect depends only on
delay. It creates the interval once per delay value. The interval function does not capturecallback. It capturessavedCallback, which is the same ref object for the whole life of the component. When the timer fires, it reads.currentand gets whatever the first effect stored most recently.
Using it looks like this:
import { useState } from 'react';
import { useInterval } from './useInterval';
export function Ticker() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
useInterval(() => {
setCount(count + step);
}, 1000);
return (
<div>
<p>{count}</p>
<button onClick={() => setStep(step + 1)}>Step: {step}</button>
</div>
);
}The interval is created once and keeps its one-second rhythm. When you click the button and change step, the next tick uses the new step. Without the pattern, either the tick would use the old step forever, or each click would restart the timer.
Passing null as delay pauses the interval, because the second effect returns early and any previous interval is cleaned up.
Why this is allowed
Earlier chapters said not to touch ref.current while rendering. This pattern follows that rule. The write to savedCallback.current happens inside an effect, which runs after React has committed the render to the screen. The read happens inside a timer callback, which is also outside rendering. Neither the render output nor the dependency list depends on the ref.
A ref write does not cause a re-render, so the update is cheap. It also means the ref is a good place for a value that the effect needs but that should not trigger the effect.
The following diagram shows the order of events.
Event listeners and other subscriptions
The same idea applies anywhere an effect registers a function with something outside React. A window listener is a common case.
import { useEffect, useRef } from 'react';
export function useWindowEvent(eventName, handler) {
const savedHandler = useRef(handler);
useEffect(() => {
savedHandler.current = handler;
});
useEffect(() => {
const listener = (event) => savedHandler.current(event);
window.addEventListener(eventName, listener);
return () => window.removeEventListener(eventName, listener);
}, [eventName]);
}The listener is added once per event name. Changing the handler does not remove and re-add the listener. This matters when the handler is an inline arrow function, because an inline function is a new object on every render.
Edge cases and gotchas
The ref lags the render by one effect
The ref updates in an effect after paint. Between the render and that effect, the ref still holds the previous callback. A timer that fires in that gap runs the older callback. For intervals and event handlers this gap is tiny and usually harmless. If your code must never see a value from before the latest commit, this pattern is not exact enough, and you should check the React version you use for newer tools built for this purpose, such as useEffectEvent, which is not yet stable in every release.
Do not assign during render as a shortcut
You might write savedCallback.current = callback directly in the component body, so there is no gap. That breaks render purity. React may render a component and then discard the result, for example in Strict Mode or in concurrent rendering. A discarded render would leave its callback in the ref, even though the screen never showed it. Keep the write inside an effect.
Effect order
Effects in one component run in the order they are written. In useInterval, the update effect comes first so the ref is current before anything else in the same commit reads it. Keep that order if you adapt the hook.
Do not use it to hide real dependencies
The pattern is for values that should not restart the effect. If a value should restart the effect, keep it in the dependency array. Here, delay is in the array because changing the delay must create a new interval. A callback is different: swapping it should never change when the timer fires.
Stale values inside the callback itself
The callback you store is still a closure over its own render. Because the ref is refreshed after every render, it is always the latest closure, so this is fine. The problem only appears if you copy a value out of the callback into another long-lived variable.
When to use it
| Situation | Better choice |
|---|---|
| Update state from its previous value inside a timer | Functional update: `setX((x) => x + 1)` |
| Effect should restart when a value changes | Put the value in the dependency array |
| Effect must stay running, but its callback reads current props or state | Latest-callback pattern |
| Value is shown on screen | State, not a ref |
Summary
A long-lived effect function sees the values from the render that created it. To give it fresh values without restarting it, store the callback in a ref, update the ref in an effect on every render, and have the long-lived function read ref.current when it runs. Keep the writes in effects, keep real dependencies in the dependency array, and accept the short gap between a render and its effect.
Exercise
In the Ticker example, why does the interval keep ticking at a steady one-second rhythm when step changes, and why does the next tick still use the new step?
Show answer
The interval effect depends only on delay, so a change in step does not restart it. The interval function reads savedCallback.current each time it fires. The first effect updates that ref after every render, so the ref holds the callback from the newest render, which closes over the new step.
Exercise
A teammate writes savedCallback.current = callback; directly in the body of useInterval, outside any effect, to remove the small gap between render and effect. What rule does this break, and what can go wrong?
Show answer
It writes to ref.current during rendering, which breaks render purity. React can render a component and discard the result, for example in Strict Mode or concurrent rendering. A discarded render would still leave its callback in the ref, so the timer could call a function from a render that was never committed to the screen.
Exercise
Write useWindowEvent-style code for a keydown listener where the handler reads a count state variable, and explain which array the eventName belongs in and why the handler does not.
Show answer
Call useWindowEvent('keydown', () => console.log(count)). Inside the hook, eventName goes in the dependency array of the listener effect, because changing the event name needs a new listener. The handler does not go there. It is stored in a ref that a separate effect updates after each render, so swapping the handler never removes and re-adds the listener.