Sub topic 15
Reading the latest values without re-running effects
This chapter assumes you know the dependency array, cleanup functions, and stale closures. You should also be comfortable with useRef.
The problem
An effect should re-run when the thing it synchronizes with changes. Sometimes it also reads a value that is not part of that synchronization. If you list the value as a dependency, the effect tears down and restarts for no good reason. If you leave it out, you get a stale closure.
Here is a timer whose tick handler reads step. Listing step restarts the interval every time step changes. Omitting it makes the interval use the first step forever.
Option 1: a ref that holds the latest value
A ref is a mutable box that survives renders and does not trigger re-renders. Update it on every render, and read it from inside the long-lived effect.
import { useEffect, useRef, useState } from 'react';
function useInterval(callback, delay) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
});
useEffect(() => {
const id = setInterval(() => callbackRef.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
function Counter() {
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 first effect has no dependency array, so it runs after every render and refreshes the ref. The second effect depends only on delay. The interval keeps running when step changes, and each tick calls the newest callback.
Effects run in the order they are declared, so the ref is updated before any later tick reads it. Do not write ref.current during rendering. Rendering must stay pure, and concurrent rendering may discard a render.
Option 2: useEffectEvent
React 19.2 added useEffectEvent. It wraps code that belongs to an event fired by an effect, and the wrapped function always sees the latest props and state. Check your React version before using it.
import { useEffect, useEffectEvent, useState } from 'react';
function Room({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
console.log(`Connected to ${roomId} using the ${theme} theme`);
});
useEffect(() => {
const id = setTimeout(() => onConnected(), 1000);
return () => clearTimeout(id);
}, [roomId]);
return <p>Room: {roomId}</p>;
}
export default function App() {
const [roomId, setRoomId] = useState('general');
const [theme, setTheme] = useState('light');
return (
<div>
<button onClick={() => setRoomId(roomId === 'general' ? 'music' : 'general')}>
Switch room
</button>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle theme
</button>
<Room roomId={roomId} theme={theme} />
</div>
);
}Changing roomId restarts the timer, because the room is what the effect synchronizes with. Changing theme does not restart it, but the log message still shows the current theme.
Rules and pitfalls
- Do not list an effect event in the dependency array. The linter knows it is not reactive.
- Call an effect event only from inside effects or from other effect events. Do not pass it to child components.
- Use these tools only for values that should not restart the effect. If a value changes what the effect connects to, keep it in the dependency array.
- Do not use a ref to silence the linter. Ask first whether the effect should re-run.
Exercise
In the Room example, roomId is read inside onConnected but is not in the effect's dependency list as an effect-event value. Why is roomId still listed in the dependency array, and what would happen if you removed it?
Show answer
The effect calls setTimeout for a particular room, so a change of room must restart it. The array lists roomId because the effect itself uses it as its trigger. If you removed it, switching rooms would not restart the timer, and the effect would stay tied to the old room.