Sub topic 6
Reading the Latest Props and State from an Effect Event
This chapter assumes you know how JavaScript closures capture variables, how useEffect and its dependency array work, and the basic useEffectEvent declaration from the previous chapter. The focus here is narrower: which values an Effect Event actually sees when it runs, and why that differs from ordinary code inside an Effect.
Closures Inside an Effect Are Snapshots
Every render of a component is a new function call. The props and state in that call are constants. An Effect created during that render closes over those constants, so any callback the Effect sets up sees the values from that one render.
Normally that is what you want. If roomId changes, the dependency array makes React clean up the old Effect and run a new one with the new closure. The problem arises when a callback reads a value that is not in the dependency array. That callback keeps the old snapshot forever, which is the stale-value bug.
Effect Events Read Values at Call Time
An Effect Event works differently. React keeps the function you pass to useEffectEvent up to date on every render. When you call the Effect Event, it runs the version from the most recent committed render. It therefore sees the latest props and state at the moment it is called, not the moment the Effect was set up.
import { useState, useEffect, useEffectEvent } from 'react';
export default function App() {
const [text, setText] = useState('');
const onLog = useEffectEvent(() => {
console.log('Latest text:', text);
});
useEffect(() => {
const id = setInterval(() => {
onLog();
}, 2000);
return () => clearInterval(id);
}, []);
return (
<input value={text} onChange={(e) => setText(e.target.value)} />
);
}Type into the input and watch the console. The interval is created once, yet every tick logs what is currently in the box. If the interval callback read text directly with an empty dependency array, it would log '' forever.
Common Mistakes
| Mistake | What actually happens |
|---|---|
| Expecting the Effect Event to see values from when the Effect started | It sees values from the latest render at call time |
| Reading a value after `await` inside the Effect Event and assuming it matches the start | The value may have changed. Capture it before awaiting if you need the original |
| Calling the Effect Event during render to get the latest value | Not allowed. Read props and state directly while rendering |
| Using "latest value" semantics for a value that should restart the Effect | The Effect never re-synchronizes for it. Keep such values as dependencies |
How React Keeps It Current
Conceptually, useEffectEvent behaves like a ref that React reassigns to your newest function before Effects run. Calling the Effect Event calls whatever the ref holds now. The ref is internal and you never touch it. React also only lets you call the Effect Event from Effects, so it never runs with values from a render that has not committed yet.
Exercise
A component has props roomId and muted. Its Effect connects to roomId and, on each incoming message, calls an Effect Event onMessage that plays a sound unless muted is true. The user toggles muted to true while connected. Will the next message play a sound, and does the connection restart?
Show answer
No sound plays, and the connection does not restart. onMessage reads muted from the latest render when it is called, so it sees true. Because muted is read only inside the Effect Event and is not a dependency, toggling it does not re-run the Effect.
Exercise
Inside an Effect Event you write const before = count; await save(); console.log(before === count);. Can this log false? Why?
Show answer
No. before and count both come from the same function closure, the one that was latest when the Effect Event was called, so the comparison is always true. To see a newer value after the await, you would need to call an Effect Event again after the await, which runs the then-latest version.