Sub topic 10
The cost of keeping hidden trees alive
This chapter assumes you know useState, useEffect and cleanup functions, and that you have read the earlier chapters on Activity, the mode prop and Effect cleanup. You need React 19.2 or later.
Keeping state alive is not free. A hidden Activity boundary holds everything the component had when it was visible: its state, its fiber tree, its DOM nodes and any data it fetched. This chapter covers what that costs, how to measure it and how to limit it.
What a hidden tree keeps
When mode is 'hidden', React does three things to the children:
- It keeps the component state and the React tree (the internal fibers that track each component).
- It keeps the DOM nodes in the page and hides them with
display: none. - It runs Effect cleanups, so subscriptions, timers and similar work stop.
Cleaning up Effects removes the ongoing work. The memory stays. Each hidden boundary holds the following:
| Resource | Held while hidden? | Notes |
|---|---|---|
| Component state and refs | Yes | Lives until the boundary unmounts. |
| Fibers (React's internal tree) | Yes | One per component instance. |
| DOM nodes | Yes | Hidden, but still in the document. |
| Event listeners attached by React | Yes | They sit on the retained DOM nodes. |
| Effect-driven work (intervals, sockets) | No | Cleanup runs on hide. |
| Work started outside Effects (media playback, listeners added without cleanup) | Maybe | Nothing stops it unless you write the cleanup. |
| Re-render work | Yes, at low priority | Covered below. |
The first four rows are the memory cost and the fifth row is the work React stops for you. The last two rows are the CPU and "forgotten side effect" costs. They are easy to miss because nothing visible changes on screen.
Memory: it grows with the number of boundaries
Memory cost scales with how many boundaries you keep and how large each tree is. A tab with a small form costs almost nothing. A tab that renders a table of 5,000 rows, a map or a large chart keeps all of that in memory.
The risk is unbounded growth. Suppose a user opens 30 documents in a viewer and you wrap each in Activity. All 30 trees stay in memory until the viewer unmounts. Browsers handle this fine on a desktop, but a low-memory phone may slow down or discard the page.
Do not ask "is Activity expensive?". Ask these questions:
- How many hidden boundaries can exist at once?
- How large is the largest one?
- Does the user come back to a hidden screen often enough to justify its memory?
If the answer to the first question is "unbounded", add a limit.
Capping the number of live boundaries
A common fix is to keep only the most recently used screens alive and let older ones unmount. The component below keeps at most three tabs alive. A tab outside that set is not rendered, so it loses its state like any conditionally rendered component.
import { Activity, useState } from 'react';
const MAX_ALIVE = 3;
export default function KeepAliveTabs({ tabs }) {
const [activeId, setActiveId] = useState(tabs[0].id);
const [recent, setRecent] = useState([tabs[0].id]);
function select(id) {
setActiveId(id);
setRecent((prev) => [id, ...prev.filter((x) => x !== id)].slice(0, MAX_ALIVE));
}
return (
<>
<nav>
{tabs.map((tab) => (
<button key={tab.id} onClick={() => select(tab.id)}>
{tab.label}
</button>
))}
</nav>
{tabs
.filter((tab) => recent.includes(tab.id))
.map((tab) => (
<Activity key={tab.id} mode={tab.id === activeId ? 'visible' : 'hidden'}>
{tab.content}
</Activity>
))}
</>
);
}Use it like this:
import KeepAliveTabs from './KeepAliveTabs';
const tabs = [
{ id: 'a', label: 'A', content: <input placeholder="Tab A" /> },
{ id: 'b', label: 'B', content: <input placeholder="Tab B" /> },
{ id: 'c', label: 'C', content: <input placeholder="Tab C" /> },
{ id: 'd', label: 'D', content: <input placeholder="Tab D" /> },
];
export default function App() {
return <KeepAliveTabs tabs={tabs} />;
}Open A, B, C and then D. Tab A drops out of the recent list and unmounts, so its text is lost. Tabs B, C and D keep theirs. The key on each Activity is stable, so evicting one tab does not remount the others.
The trade-off is that the user sometimes loses state, but only in tabs they have not touched recently. Pick the limit from the size of your trees. You can also evict by size or by age instead of count.
CPU: hidden trees still render
Hidden does not mean frozen. When props, context or a parent's state change, React still re-renders hidden children so they are up to date when shown again. It does this at a lower priority than visible work. Hidden updates wait until React has finished the urgent updates for the visible UI, such as typing and clicks.
Low priority protects responsiveness. It does not remove the work. If a parent updates 60 times a second and passes a new prop to ten hidden trees, React queues renders for all ten. They run when the main thread is free, but a busy page may rarely be free.
The next example shows the effect. The hidden Report re-renders on every tick because its parent passes it a new prop.
import { Activity, useEffect, useState } from 'react';
function Report({ tick }) {
console.log('Report rendered, tick =', tick);
return <p>Tick: {tick}</p>;
}
export default function App() {
const [tick, setTick] = useState(0);
const [show, setShow] = useState(false);
useEffect(() => {
const id = setInterval(() => setTick((t) => t + 1), 1000);
return () => clearInterval(id);
}, []);
return (
<>
<button onClick={() => setShow(!show)}>Toggle report</button>
<Activity mode={show ? 'visible' : 'hidden'}>
<Report tick={tick} />
</Activity>
</>
);
}Open the console with the report hidden. You should see log lines continue, even though nothing is on screen. React is keeping the hidden tree current. The setInterval in App is outside the boundary, so it keeps running. Only Effects inside the hidden boundary are cleaned up.
Reducing hidden render work
You have four options, from cheapest to most invasive:
- Stop passing frequently changing props. Pass them only to the visible screen, or read them from a store inside the screen.
- Use
React.memo. If a hidden component receives the same props, React skips its render. - Keep fast-changing state low. State that lives inside a screen changes only that screen. State lifted to the parent invalidates every child.
- Unmount instead. If a screen is both heavy and busy, hiding it costs more than rebuilding it later.
Check the numbers with the React DevTools Profiler before changing anything. Look at how often hidden components appear in commits and how long they take.
Pre-rendering has a cost too
An Activity that starts as 'hidden' renders its children for the first time at low priority, without mounting Effects. This is the pre-rendering feature from the previous chapter. It makes the first reveal fast, because the tree is already built.
The cost is that you pay for the render before the user asks for it. If the user never opens the screen, that work is wasted. It also competes for the main thread, though at low priority. Pre-render only what the user is likely to open next.
Data loading adds a second cost. Code that fetches data in a way that works with Suspense can start fetching while the tree is hidden. That makes the reveal faster, but it also uses bandwidth and server capacity for screens that may never be seen. Apply the same rule as for rendering. Pre-render the likely next screen, not every screen.
Costs that cleanup does not cover
React cleans up the Effects it knows about. It cannot clean up everything. Three cases need your attention.
Work started outside an Effect. A <video> that is playing keeps playing when its panel is hidden, because the DOM node still exists. Fix it with a cleanup that pauses it:
import { useLayoutEffect, useRef } from 'react';
function VideoPanel() {
const videoRef = useRef(null);
useLayoutEffect(() => {
const video = videoRef.current;
return () => {
video.pause();
};
}, []);
return <video ref={videoRef} controls src="/clip.mp4" />;
}Audio elements, <iframe> content and canvas animations driven by requestAnimationFrame outside an Effect need the same treatment.
Listeners and timers outside React's control. If code attaches a window listener when a component renders, or in an event handler, nothing removes it when the boundary hides. Move that code into an Effect with cleanup.
Large retained objects. State that holds a big array, a decoded image or a parsed document stays in memory while hidden. If the user can rebuild it cheaply, store less. For example, keep the document ID in state and load the content from a cache.
Choosing how long to keep a screen
Use the diagram as a first filter. It does not replace measurement.
A few rules of thumb follow from this:
- Keep alive the screens with state that is expensive to recreate. Examples are long forms, scroll positions in large lists and partly completed wizards.
- Unmount screens that are cheap to rebuild or rarely revisited.
- Prefer a small lifted state (such as a filter string) over keeping a whole tree alive just to remember one value.
- Do not wrap every route in
Activityby default. Add it where losing state hurts.
Common mistakes
- Treating hidden as free. Memory and low-priority renders still count. Profile a realistic session, not a single tab switch.
- Unbounded boundaries. Rendering one
Activityper item in a growing list (documents, chat threads, search results) leaks memory over time. Cap it. - Assuming all side effects stop. Only Effect cleanups run. Media, manual listeners and work outside Effects continue.
- Changing the key to "reset" a hidden screen. A new
keycreates a new instance, so the old one unmounts and its state is lost. This is the correct way to discard a screen, but do it deliberately. - Passing fast-changing props to hidden screens. This keeps them re-rendering for no visible benefit.
Practice
Exercise
A document viewer wraps every open document in its own Activity boundary. After a long session with 40 open documents, the page becomes sluggish on phones. Name the two costs behind this and one change that fixes it without removing Activity entirely.
Show answer
The two costs are memory and render work. Each hidden document keeps its fibers, DOM nodes and state in memory, and React still re-renders hidden documents at low priority when their props or context change. A fix is to cap the number of live boundaries, for example keeping only the three most recently used documents inside Activity and unmounting older ones. Keeping only a document ID in state and loading the content from a cache also reduces what each hidden tree holds.
Exercise
A hidden settings panel contains a component that calls window.addEventListener('resize', handler) directly in its render body. After the panel is hidden, the handler keeps running. Why does Activity not stop it, and how do you fix it?
Show answer
Activity only runs the cleanup functions of Effects. A listener added during render or in an event handler has no cleanup, so nothing removes it when the boundary hides. Move the code into a useEffect that adds the listener and returns a cleanup function that calls window.removeEventListener with the same handler. After that, hiding the boundary removes the listener and showing it adds it again.