Lesson 22 of 37Modern React
useEffectEvent and Activity
Separate reactive from non-reactive logic in effects with useEffectEvent, and keep hidden UI alive without its effects using Activity.
A chat screen connects to a room when it opens. A month later someone adds a toast that says "Connected" in the user's chosen theme, reads theme inside the effect, and adds it to the dependency array because the linter asked. Now every theme switch tears down the socket and reconnects. Nobody notices until support tickets mention dropped messages. React 19.2 shipped two tools that fix whole classes of bugs like this one: useEffectEvent, which lets an effect read the latest values without reacting to them, and <Activity>, which hides part of the UI while keeping its state and switching its effects off.
The over-firing effect
You learned in useEffect that an effect is a synchronization: "while this component is on screen, keep the connection matching roomId". Every reactive value the effect reads must be in the dependency array, because otherwise the effect keeps using a stale copy from an old render. That rule is correct, and it is also where the trouble starts.
function ChatRoom({ roomId, theme }: { roomId: string; theme: Theme }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.on("connected", () => {
showNotification("Connected!", theme);
});
connection.connect();
return () => connection.disconnect();
}, [roomId, theme]); // theme is here only because the toast reads it
}Look at what the effect does. The connection depends on roomId. The toast depends on theme. But they are not the same kind of dependency. Changing rooms should reconnect. Changing the theme should not, it should only affect the next toast. The effect mixes reactive logic (connect to this room) with non-reactive logic (when you happen to connect, read whatever the theme is right now).
Before 19.2 you had three bad choices:
- List
themeand accept the reconnects. - Leave it out and silence the linter. The toast now uses the theme from the first render forever. That is the stale closure bug from Refs, and it hides well because it only shows up after a change.
- Copy it into a ref in a layout effect and read
themeRef.current. This works, and many codebases have auseLatestoruseEventhelper doing exactly that, but it is boilerplate, easy to get subtly wrong, and invisible to the linter.
useEffectEvent
useEffectEvent wraps a piece of logic so it always sees the latest props and state when it runs, while being non-reactive itself. You pull the toast out into an Effect Event and call it from the effect.
function ChatRoom({ roomId, theme }: { roomId: string; theme: Theme }) {
const onConnected = useEffectEvent(() => {
showNotification("Connected!", theme); // always the current theme
});
useEffect(() => {
const connection = createConnection(roomId);
connection.on("connected", () => onConnected());
connection.connect();
return () => connection.disconnect();
}, [roomId]); // only what the connection depends on
}The name is deliberate. An Effect Event is like an event handler: it fires in response to something (here, the socket saying "connected") and reads the current state at that moment. The difference is that a normal event handler is fired by the user, and an Effect Event is fired from inside an effect.
Try it. Switch the theme a few times and watch the console: there is no reconnect. Then switch rooms: the connection is replaced, and the new notice uses whatever theme is current.
ChatRoom mounts with roomId general and theme light. Then theme changes to dark. Then roomId changes to random. No StrictMode. What is logged?
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
console.log("toast " + theme);
});
useEffect(() => {
console.log("connect " + roomId);
onConnected();
return () => console.log("disconnect " + roomId);
}, [roomId]);
return null;
}The rules
Effect Events are a sharp tool, and the rules are tight on purpose.
- Call them only from inside effects (
useEffect,useLayoutEffect,useInsertionEffect), or from callbacks those effects set up, like the socket handler above or asetTimeoutstarted in the effect. Calling one during render is an error, and React tells you so. - Do not pass them to other components or hooks. Declare the Effect Event right next to the effect that uses it. A child that receives one cannot know it is non-reactive.
- Do not list them in dependency arrays. They are not reactive values.
- Do not use them to silence the linter. If the effect really should re-run when a value changes, that value is reactive and belongs in the array.
The current eslint-plugin-react-hooks understands all of this. exhaustive-deps does not ask you to add an Effect Event to the array, and the rules-of-hooks check reports an Effect Event that is called outside an effect or passed somewhere else. Keep the plugin on its recommended preset and upgrade it with React.
The question to ask for each value an effect reads is: "Should a change to this value re-run the synchronization?" If yes, it is a dependency. If no, and the value is only read when something happens, move that read into an Effect Event.
| Value | Re-sync when it changes? | Where it goes |
|---|---|---|
roomId for a chat connection | Yes, new room needs a new socket | Dependency array |
theme for a toast shown on connect | No | Effect Event |
cartCount logged with a page view analytics event | No, log the current value | Effect Event |
url for a page view analytics event | Yes, a new page is a new view | Dependency, passed as an argument |
muted for a "new message" sound | No | Effect Event |
That fourth row shows a useful pattern: you can pass reactive values as arguments to the Effect Event. onVisit(url) makes it obvious that the visit is tied to url, while cartCount inside is read fresh.
const onVisit = useEffectEvent((visitedUrl: string) => {
logVisit(visitedUrl, cartCount);
});
useEffect(() => {
onVisit(url);
}, [url]);useEffectEvent is wrong?How it works underneath
An Effect Event is a function whose implementation React swaps on every commit. During render you hand useEffectEvent a fresh closure that captured this render's props and state. When React commits, before your effects run, it stores that closure as the current one. The function your effect holds is a thin wrapper that always calls whatever closure is current.
That is why calling it during render is forbidden: during render, the "current" closure might belong to a render that never commits (a transition can be thrown away, and Suspense can retry). Only after commit is "latest" well defined. The ref-plus-layout-effect helper people wrote by hand did the same thing, but it updated in a layout effect, so child layout effects that ran first could see the previous closure. React doing it internally closes that gap.
Activity: hide without unmounting
The second half of this lesson is about a different problem with the same theme: controlling when effects run. Picture a dashboard with tabs. The user types half a filter into the Reports tab, switches to Settings, then comes back. With the usual conditional rendering, {tab === "reports" && <Reports />}, the Reports tree unmounts when hidden. The half-typed filter, the scroll position and any loaded chart are gone.
The old workaround was to keep every tab mounted and hide the inactive ones with CSS. State survives, but every hidden tab keeps running: its intervals tick, its subscriptions stay open, and every update re-renders it at full priority while the user is looking at something else.
<Activity> gives you a third option:
import { Activity } from "react";
<Activity mode={tab === "reports" ? "visible" : "hidden"}>
<Reports />
</Activity>When the mode becomes "hidden", React:
- hides the children with
display: none, so the DOM stays in the page, - keeps their state, and the DOM keeps things like input values,
- runs the cleanup of every effect inside, as if the tree unmounted,
- keeps rendering the children when their props change, but at the lowest priority, after all visible work.
When it becomes "visible" again, React shows the DOM and runs the effects' setup again. To the components inside, being hidden looks like an unmount and being shown looks like a mount, except their state never went away.
The user switches tabs. The parent renders <Activity mode="hidden"> around the old panel.
Type something in each tab, switch, and watch the console. Then untick Use Activity to compare with conditional rendering, where every switch throws the state away.
Notice the seconds counter pauses while a panel is hidden. The interval was cleaned up, exactly like an unmount, and set up again on show.
Pre-rendering the next screen
Activity has a second use. A hidden boundary that has never been shown still renders its children, in the background, at low priority. You can use that to pre-render a screen the user is likely to open next: the second step of a checkout, the tab most people click after the first.
<Activity mode={step === "shipping" ? "visible" : "hidden"}>
<ShippingStep />
</Activity>There is a catch that trips people up. While hidden, effects do not run. If ShippingStep loads its data in a useEffect, pre-rendering loads nothing and the user still waits. Data that loads through Suspense (a framework loader, use with a cached promise, a library with Suspense support) does load during the hidden render. This is one more reason the data-fetching lesson pushed you away from fetch-in-effect.
Choosing between the options
| Approach | State kept? | Effects while hidden | Cost while hidden |
|---|---|---|---|
Conditional rendering {show && <X />} | No | None (unmounted) | Nothing |
CSS hide (hidden, display: none) | Yes | Keep running | Full: effects and normal-priority renders |
<Activity mode="hidden"> | Yes | Cleaned up | DOM and state in memory, low-priority renders |
Changing a key | No, reset on purpose | Remounted | Nothing |
Conditional rendering is still the right default for most things, like a modal or a dropdown that should start fresh each time. Reach for Activity when losing state would annoy the user: tabs, a sidebar that collapses, a list you navigate away from and back to.
Match each requirement to the approach that fits it best.
Edge cases seniors watch for
- DOM side effects that are not effects. A playing
<video>or<audio>element keeps playing underdisplay: none, because hiding it is not pausing it. Add an effect whose cleanup pauses it. AuseLayoutEffectcleanup runs before the hide, so the pause happens in the same frame. - Memory. Hidden trees hold their DOM and state. Ten hidden tabs with large tables cost real memory. Keep the set small, or drop old ones back to conditional rendering.
- Effects that assume they run once. Activity makes the StrictMode double run from the useEffect lesson real: a component inside can be "unmounted" and "mounted" many times while its state lives on. If setup and cleanup are symmetrical, this just works.
- Focus. If the focused element ends up inside a boundary that goes hidden, move focus to something sensible in the newly shown content.
A tab inside <Activity> has an effect that subscribes to a store. Put the events in order as the user switches away and comes back.
- Tap the steps below in the right order.
Two more 19.2 tools worth knowing
cacheSignal is for Server Components only. On the server, cache() deduplicates work for the lifetime of one render. cacheSignal() returns an AbortSignal that fires when that lifetime ends, because the render finished, was aborted, or failed. Pass it to fetch so work nobody will use is cancelled:
import { cache, cacheSignal } from "react";
export const getUser = cache((id: string) =>
fetch(`https://api.example.com/users/${id}`, { signal: cacheSignal() }),
);Performance Tracks, which you met in Performance, add React's Scheduler and Components tracks to the Chrome DevTools Performance panel. They are also the tool for the features in this lesson. When someone says "the tab switch feels slow", record a profile and look there before guessing. You can see whether a hidden Activity pre-render was really deferred, or whether a transition kept getting interrupted.
<Activity mode="hidden">. Reviews load with useEffect(() => fetch(...)). The user opens the tab. What do they see?- reactive value
- Props, state and anything computed from them during render. An effect that reads one must list it as a dependency.
- Effect Event
- A function made with
useEffectEventthat reads the latest props and state but is not reactive, so it is never a dependency. Call it only from effects. - stale closure
- A function that captured values from an old render and keeps using them after they changed.
- Activity
- A component whose
modeprop isvisibleorhidden. Hidden children keep their state and DOM, have their effects cleaned up, and render at low priority. - pre-rendering
- Rendering a likely next screen inside a hidden Activity so it is ready when shown. Only Suspense-based data loads during it.
- cacheSignal
- A Server Components API that returns an AbortSignal which aborts when the current
cache()lifetime ends. - Performance Tracks
- React's custom tracks in the Chrome DevTools Performance panel, showing scheduler priorities and component work.