Skip to content

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.

15 min read0/5 questions

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.

ChatRoom.tsx (the bug)
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 theme and 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 a useLatest or useEvent helper 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.

ChatRoom.tsx (fixed)
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.

ReactEffectEvent.tsx
import { useEffect, useEffectEvent, useState } from "react"; function createConnection(roomId: string) { let timer: ReturnType<typeof setTimeout> | undefined; return { connect(onOpen: () => void) { console.log(`connect #${roomId}`); timer = setTimeout(onOpen, 400); }, disconnect() { clearTimeout(timer); console.log(`disconnect #${roomId}`); }, };} function ChatRoom({ roomId, theme }: { roomId: string; theme: string }) { const [notice, setNotice] = useState("Connecting..."); const onConnected = useEffectEvent(() => { setNotice(`Connected to #${roomId}, toast styled ${theme}`); }); useEffect(() => { const connection = createConnection(roomId); connection.connect(() => onConnected()); return () => connection.disconnect(); }, [roomId]); const dark = theme === "dark"; return ( <p style={{ padding: 12, background: dark ? "#222" : "#eef", color: dark ? "#fff" : "#000" }}>{notice}</p> );} export default function App() { const [roomId, setRoomId] = useState("general"); const [theme, setTheme] = useState("light"); return ( <div> <select value={roomId} onChange={(e) => setRoomId(e.target.value)}> <option value="general">general</option> <option value="random">random</option> <option value="music">music</option> </select>{" "} <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Theme: {theme}</button> <ChatRoom roomId={roomId} theme={theme} /> </div> );}
Predict the outputJavaScript

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;
}
Need a nudge? Hints walk you through it.

The rules

Effect Events are a sharp tool, and the rules are tight on purpose.

  1. Call them only from inside effects (useEffect, useLayoutEffect, useInsertionEffect), or from callbacks those effects set up, like the socket handler above or a setTimeout started in the effect. Calling one during render is an error, and React tells you so.
  2. 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.
  3. Do not list them in dependency arrays. They are not reactive values.
  4. 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.

ValueRe-sync when it changes?Where it goes
roomId for a chat connectionYes, new room needs a new socketDependency array
theme for a toast shown on connectNoEffect Event
cartCount logged with a page view analytics eventNo, log the current valueEffect Event
url for a page view analytics eventYes, a new page is a new viewDependency, passed as an argument
muted for a "new message" soundNoEffect 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]);
Quick check
Which use of useEffectEvent is wrong?
Need a nudge? A hint rules out a wrong answer.
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.

An Activity boundary going hidden and back
ParentReactPanelDOMmode: hiddendisplay: nonerun effect cleanupsnew props while hiddenmode: visibleshow nodesrun effect setups

The user switches tabs. The parent renders <Activity mode="hidden"> around the old panel.

1/7

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.

ReactActivityTabs.tsx
import { Activity, useEffect, useState } from "react"; function Panel({ name }: { name: string }) { const [seconds, setSeconds] = useState(0); const [draft, setDraft] = useState(""); useEffect(() => { console.log(`${name}: effect setup`); const id = setInterval(() => setSeconds((s) => s + 1), 1000); return () => { console.log(`${name}: effect cleanup`); clearInterval(id); }; }, [name]); return ( <div style={{ marginTop: 12 }}> <p>{name} has been visible for {seconds}s</p> <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder={`Notes for ${name}`} /> </div> );} const TABS = ["Inbox", "Reports"]; export default function App() { const [tab, setTab] = useState("Inbox"); const [useActivity, setUseActivity] = useState(true); return ( <div> <label> <input type="checkbox" checked={useActivity} onChange={(e) => setUseActivity(e.target.checked)} /> Use Activity </label> <div style={{ display: "flex", gap: 8, marginTop: 8 }}> {TABS.map((t) => ( <button key={t} aria-pressed={tab === t} onClick={() => setTab(t)} style={{ fontWeight: tab === t ? 700 : 400 }}> {t} </button> ))} </div> {useActivity ? TABS.map((t) => ( <Activity key={t} mode={tab === t ? "visible" : "hidden"}> <Panel name={t} /> </Activity> )) : <Panel key={tab} name={tab} />} </div> );}

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

ApproachState kept?Effects while hiddenCost while hidden
Conditional rendering {show && <X />}NoNone (unmounted)Nothing
CSS hide (hidden, display: none)YesKeep runningFull: effects and normal-priority renders
<Activity mode="hidden">YesCleaned upDOM and state in memory, low-priority renders
Changing a keyNo, reset on purposeRemountedNothing

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 the pairs0/4 matched

Match each requirement to the approach that fits it best.

Choose an item, then its match on the other side.

Edge cases seniors watch for

  • DOM side effects that are not effects. A playing <video> or <audio> element keeps playing under display: none, because hiding it is not pausing it. Add an effect whose cleanup pauses it. A useLayoutEffect cleanup 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.
Put it in order5 steps

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.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

lib/data.ts (server only)
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.

Quick check
A product page pre-renders the reviews tab with <Activity mode="hidden">. Reviews load with useEffect(() => fetch(...)). The user opens the tab. What do they see?
Need a nudge? A hint rules out a wrong answer.
Key terms
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 useEffectEvent that 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 mode prop is visible or hidden. 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.