Sub topic 15
Reading the latest values without re-running effects
This chapter assumes you know useState, the dependency array, cleanup functions, and how a stale closure captures old values. If any of those are unclear, review the chapters on dependencies and stale closures first.
The problem: reactive values you do not want to react to
The dependency array rule is simple. Every prop, state value, or derived value that an effect reads must be listed, and the effect re-runs when any of them changes. That rule is correct for synchronization. Sometimes, though, an effect reads a value that it should not re-run for.
Here is a page-visit logger. The log should fire when url changes. It also reports how many items are in the cart.
import { useEffect } from 'react';
function Page({ url, cartItems }) {
useEffect(() => {
console.log(`Visited ${url} with ${cartItems.length} items in cart`);
}, [url, cartItems]);
return <p>Current page: {url}</p>;
}This code is honest about its dependencies, but the behavior is wrong. Every time the cart changes, the effect runs again and logs a second "visit" to the same URL.
You have three bad options:
- Remove
cartItemsfrom the array. The linter warns, and the effect may log an outdated cart if the code changes later. - Move the log into an event handler. There is no event here. The log is tied to the page being shown, which is why it is an effect.
- Add a guard comparing the previous URL. This works, but it adds bookkeeping that you have to maintain.
The cleaner approach is to separate the two roles. url is something the effect reacts to. cartItems is something the effect only reads.
Reactive code versus event-like code
React documentation describes this split as two kinds of logic inside an effect:
| Kind | Behavior | Example |
|---|---|---|
| Reactive | Should cause the effect to re-run when it changes | `url`, `roomId`, `userId` |
| Event-like | Should run at a specific moment and always see current values | "log the visit", "show a notification" |
An event handler always sees the latest props and state because it is recreated on every render. An effect's code is captured by the render that created it. The tools in this chapter give a piece of effect code the "latest value" behavior of an event handler.
Fix 1: `useEffectEvent`
useEffectEvent wraps a function so it always reads the latest props and state, without becoming a dependency. It is available in React 19.2 and later. On older versions it was experimental, so check your installed version before relying on it.
import { useEffect, useEffectEvent } from 'react';
function Page({ url, cartItems }) {
const onVisit = useEffectEvent((visitedUrl) => {
console.log(`Visited ${visitedUrl} with ${cartItems.length} items in cart`);
});
useEffect(() => {
onVisit(url);
}, [url]);
return <p>Current page: {url}</p>;
}The effect depends only on url. When the cart changes, the effect does not run. When url changes, onVisit runs and reads the cart from the most recent render.
Rules for effect events:
- Call them only from inside effects (or from other effect events). Do not call them during rendering or from event handlers.
- Do not pass them to child components or other hooks as props or callbacks. They are meant to be local to the effect that uses them.
- Do not list them in the dependency array. They are intentionally not reactive, and the
react-hookslint rule knows this. - Declare them in the same component as the effect, close to the effect.
Fix 2: the latest-ref pattern
Before useEffectEvent, the standard workaround was a ref that always holds the newest value. A ref is a stable object. Its .current can change without causing a re-render, and the ref object itself never needs to be a dependency.
This version of an interval hook accepts a callback that may change every render:
import { useEffect, useRef, useState } from 'react';
function useInterval(callback, delayMs) {
const callbackRef = useRef(callback);
useEffect(() => {
callbackRef.current = callback;
});
useEffect(() => {
if (delayMs === null) return;
const id = setInterval(() => callbackRef.current(), delayMs);
return () => clearInterval(id);
}, [delayMs]);
}
function Ticker({ step }) {
const [total, setTotal] = useState(0);
useInterval(() => {
setTotal(total + step);
}, 1000);
return <p>Total: {total}</p>;
}Walk through what happens:
- 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
delayMs. The interval is created once and is not reset whencallbackchanges. - Each tick calls
callbackRef.current(), which is the callback from the latest committed render. It sees the currenttotalandstep.
Without the ref, you would list callback in the dependencies. A new inline function is created on every render, so the interval would be cleared and restarted constantly. A timer that restarts on every state change can then fail to fire at all.
Choosing between the two
The two approaches behave the same in most cases. useEffectEvent states the intent in the code and is checked by the linter. The ref pattern works in every React version and can live inside a reusable hook, as useInterval shows. A third alternative sometimes removes the need for either, covered next.
Alternatives to check first
Before reaching for either tool, check whether a simpler fix is available.
- Functional state updates. If you only need the previous state to compute the next state, use
setCount((c) => c + 1). The effect then needs nocountdependency. The timer example in an earlier chapter does exactly this. - Move the code out of the effect. If the logic responds to a click or submit, it belongs in an event handler, which already sees current values.
- Move the value inside the effect. If an object or function is only used by one effect, create it inside the effect so it is not a dependency.
- Split the effect. If one effect mixes two unrelated jobs, give each its own effect and its own dependencies.
Use latest-value tools only when the effect truly has one reactive trigger and one value it must read at that moment.
Edge cases and gotchas
The value is read at call time, not at effect start. With either tool, the function sees the latest committed render when it is called. For a callback fired later by a socket or timer, that is usually what you want. If you need the value as it was when the effect started, read it into a local constant inside the effect instead.
Ref updates lag by one commit. In the useInterval example, the ref is updated in an effect after the render commits. A tick that fires between render and effect would see the previous callback. For timers at normal speeds this is not noticeable. If it matters, update the ref in useLayoutEffect, which runs before the browser paints.
Do not use a ref to hide real dependencies. Suppose an effect connects to a room, and you store roomId in a ref so the connection is not recreated. The connection then stays on the old room after the prop changes. That is a bug that the lint rule exists to prevent. Keep any value that defines what the effect connects to in the dependency array.
Strict Mode still applies. In development, React mounts, unmounts, and mounts again. Your effect events and refs are re-created along with the component, so they behave correctly. Your effect must still have a working cleanup.
Effect events are not memoized callbacks. Do not use useEffectEvent as a replacement for useCallback. Its identity is not stable, so passing it as a prop or into a dependency array is both wrong and flagged by the linter.
Summary
- Dependencies describe what an effect synchronizes with. Some values are just read, and they should not restart the effect.
useEffectEventmarks reading code as event-like, so it sees the latest values and stays out of the dependency array.- The latest-ref pattern gives the same result in older versions of React. Update the ref in an effect, never during render.
- Try functional updates, event handlers, and effect splitting first. They often remove the problem entirely.
Exercise
A component has useEffect(() => { socket.emit('join', roomId); showToast(Joined ${roomId} (${theme})); return () => socket.emit('leave', roomId); }, [roomId, theme]);. Changing the theme causes the user to leave and rejoin the room. Rewrite the effect using useEffectEvent so that only roomId triggers the join and leave.
Show answer
Put the toast in an effect event and depend only on roomId. For example: const onJoined = useEffectEvent((id) => { showToast(Joined ${id} (${theme})); }); then useEffect(() => { socket.emit('join', roomId); onJoined(roomId); return () => socket.emit('leave', roomId); }, [roomId]);. The toast reads the latest theme when called, and a theme change no longer reruns the effect. roomId stays in the array because it defines what the effect connects to.
Exercise
Why should the latest-ref pattern assign callbackRef.current inside an effect instead of in the component body?
Show answer
Assigning during render is a side effect in a function that must be pure. React may start a render and discard it, for example under concurrent rendering, so the ref could hold a value from a render that never committed. Assigning inside an effect runs only after a render commits, so the ref always holds a committed value.
Exercise
A teammate wants to put userId in a ref and remove it from the dependencies of an effect that fetches /api/users/${userId}, to avoid extra fetches. What goes wrong, and what is the better approach?
Show answer
The effect would fetch once and never refetch when userId changes, so the screen shows stale data for the wrong user. userId defines what the effect synchronizes with, so it must stay in the dependency array. If extra fetches are the concern, add cleanup that aborts the earlier request, or use caching in a data-fetching library.