Sub topic 6
Reading the Latest Props and State from an Effect Event
This chapter assumes you know how JavaScript closures capture variables. You should also know how a function component re-renders with new props and state, and how to declare an Effect Event with useEffectEvent, which the previous chapter covered. Here the question is narrower: when an Effect Event runs, which values does it see, and why?
The short answer is that an Effect Event always sees the props and state from the most recently committed render. It does not see the render that created the Effect. That one property is the whole reason Effect Events exist, and it comes with some edge cases you should understand before relying on it.
Two Kinds of Closures in One Component
Every render of a function component is a separate function call. Each call has its own props, its own state values, and its own set of inner functions. Those inner functions close over that render's values.
An Effect's setup function is one of those inner functions. When React runs the setup, it uses the version created during the render that triggered it. Any callback the setup registers, such as a connected listener, an interval tick, or a .then handler, closes over that same render's values. If the Effect does not re-run, those callbacks keep the old values for as long as they live.
An Effect Event behaves differently. You still write it as an inner function that closes over the current render's values. The difference is that React swaps in the newest version after each commit. When you call it, you get the version from the latest committed render, no matter when the calling code was set up.
| Function | Closes over | Updated when |
|---|---|---|
| Effect setup and callbacks it registers | The render that ran the Effect | Only when the Effect re-runs |
| Event handler passed to JSX | The render that produced the JSX | Every render, because React attaches the new handler |
| Effect Event | The latest committed render | After every commit, before that commit's Effects run |
Seeing the Difference
The following component makes the two behaviors visible side by side. The Effect runs once on mount and schedules a log every two seconds. Each tick prints the text value captured by the Effect's closure and the value an Effect Event reads.
import { useState, useEffect, useEffectEvent } from 'react';
export default function LatestValueDemo() {
const [text, setText] = useState('');
const readText = useEffectEvent(() => {
return text;
});
useEffect(() => {
const capturedText = text; // value from the mount render
const id = setInterval(() => {
console.log('captured:', JSON.stringify(capturedText));
console.log('latest: ', JSON.stringify(readText()));
}, 2000);
return () => clearInterval(id);
// Deliberately runs once. `text` is read only at setup time,
// to show what a closure from the mount render sees.
}, []);
return (
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type and watch the console"
/>
);
}Type "hello" into the input and watch the console. The captured line always prints "" because that is what text was during the mount render. The latest line prints "hello" because readText is the version from the most recent render.
This demo also shows that an Effect Event can return a value. Most Effect Events perform a side effect, but returning a computed value from the latest render is allowed.
What "Latest" Means Precisely
"Latest" means the latest render React has committed to the screen. It does not mean the latest state you requested. This difference produces a few edge cases.
Pending state updates are not visible yet
When you call a state setter, React schedules a re-render. It does not change the variable in the current closure. If an Effect Event sets state and then reads it in the same call, it sees the old value.
import { useState, useEffect, useEffectEvent } from 'react';
export default function PendingUpdate() {
const [count, setCount] = useState(0);
const onTick = useEffectEvent(() => {
setCount(count + 1);
console.log('count right after setCount:', count); // still the old value
});
useEffect(() => {
const id = setInterval(() => onTick(), 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}The log trails the screen by one each time. The next tick sees the new value because a render has been committed in between. If you need the next value immediately, compute it in a local variable (const next = count + 1) and use that variable for both the setter and the log.
Renders that never commit are skipped
With concurrent rendering, React can start a render and throw it away. Examples include a transition that gets interrupted or a component that suspends. An Effect Event is never updated from a render that did not commit. This is why React swaps the function during the commit and not during rendering. A callback that fires while such a render is in progress still sees the last committed values, which match what the user sees on screen.
Effects in the same commit see that commit's values
React updates Effect Events before it runs the Effects of the same commit. If a render changes roomId and theme together, the Effect that reconnects for the new roomId calls an Effect Event that already sees the new theme. You never get a mix where the Effect has fresh values and the Effect Event has stale ones.
Values are read at call time, not at setup time
An Effect Event reads values when it is called. That point can be long after the Effect set things up. In the chat example from earlier chapters, showNotification('Connected!', theme) uses the theme that is current when the server confirms the connection. If the user switches the theme while the connection is still opening, the notification uses the new theme. Usually that is what you want. If you need the value from setup time, read it in the Effect and pass it in as an argument. The next chapter covers that pattern.
Mutable objects show their current contents
An Effect Event gets the latest reference to a prop or state value. If that value is an object that someone mutates in place, the Effect Event sees whatever the object holds at call time. Mutation never triggers a render, so the reference can be stale even after the contents have changed. This is one more reason to treat props and state as immutable.
A Mental Model of the Mechanism
You can approximate the behavior with a ref that is updated during each commit. The following Hook is a simplified model and not React's real implementation, but it explains the semantics.
import { useRef, useInsertionEffect, useCallback } from 'react';
export function useEffectEventModel(fn) {
const latest = useRef(fn);
// Runs during commit, before regular and layout Effects.
useInsertionEffect(() => {
latest.current = fn;
});
return useCallback((...args) => latest.current(...args), []);
}Each render passes a new fn that closes over that render's values. The insertion Effect copies it into the ref only after a commit, so renders that never commit cannot leak into it. The returned wrapper always calls whatever the ref currently holds.
The built-in useEffectEvent is still different from this model in ways that matter:
- It throws if you call it during rendering. The model would quietly run the previous render's version.
- React does not promise a stable identity for the returned function. Code that compares it, memoizes on it, or lists it as a dependency is relying on behavior you are not supposed to depend on.
- The dependency linter recognizes the built-in Hook and keeps its result out of dependency arrays. It does not recognize a hand-written version.
Why This Fixes Stale Closures Without Re-synchronizing
Before Effect Events, you had two bad choices for a long-lived callback that needed a current value. You could add the value to the dependencies, which tears down and rebuilds the connection, timer, or subscription every time the value changes. Or you could leave it out, and the callback would read a stale value. Effect Events remove that trade-off. The Effect's dependencies decide when the external resource is rebuilt. The Effect Event decides which values the callback reads, and it always reads current ones.
Exercise
A component renders with volume = 3, and its Effect starts an interval that calls an Effect Event logging volume. The user drags a slider, and the component re-renders with volume = 7. The Effect's dependency array does not include volume. What does the next tick log, and does the interval restart?
Show answer
It logs 7. React swapped in the Effect Event from the volume = 7 render during that commit. The interval does not restart, because volume is not a dependency of the Effect and the Effect did not re-run.
Exercise
Inside an Effect Event, you write setItems([...items, newItem]); sendCount(items.length);. The server receives a count that is one lower than expected. Why, and how do you fix it?
Show answer
The setter schedules a re-render but does not change items in the current call, so items.length is still the old count from the latest committed render. Compute the next array first with const next = [...items, newItem], then call setItems(next) and sendCount(next.length).
Exercise
A teammate replaces useEffectEvent with the useEffectEventModel Hook from this chapter and also calls the returned function directly in the component body to compute a label. What goes wrong, and what would the built-in Hook do?
Show answer
During rendering, the ref still holds the previous committed render's function, because the insertion Effect has not run yet for this render. The label is computed from stale values. The built-in useEffectEvent throws when it is called during render, which exposes the mistake right away. Values used for rendering should be computed directly in the component body instead.