Sub topic 10
The cost of keeping hidden trees alive
This chapter assumes you know useState, useEffect cleanup, and the mode prop of Activity from earlier chapters. Here you will learn what a hidden Activity costs and how to keep that cost under control.
What "hidden" still holds
A hidden Activity is not free. React keeps the whole subtree in memory so it can show it again instantly. That subtree holds:
- The component state and refs.
- The fiber tree, which is React's internal record of every component.
- The DOM nodes, which stay in the page but are hidden from view.
Effects are the one thing React releases. Their cleanup functions run when the boundary hides, so timers and subscriptions stop. Memory is not released.
Where the cost comes from
There are three separate costs.
| Cost | Cause | Grows with |
|---|---|---|
| Memory | State, fibers, and DOM nodes stay alive | Number and size of hidden trees |
| Render work | Hidden trees still re-render when their props or context change | Frequency of updates above them |
| Initial work | Hidden content is rendered once up front | Number of boundaries mounted at the start |
Hidden trees update at lower priority. That keeps visible UI responsive, but the work still happens. A hidden tree that reads a context changing every second will re-render every second, just later and in idle time.
Common mistake: wrapping everything
A common error is to wrap every route or tab in Activity because state loss is annoying. In an app with 30 screens, you then keep 30 trees alive. Each one keeps its DOM and state, and each re-renders when shared context changes.
A second error is hiding state that is cheap to recreate. A static help page has no typed text to lose, so keeping it alive costs memory and gains nothing.
A third error is storing large data in state of hidden screens. A hidden screen holding a 50,000-row table keeps that table until it unmounts.
Limiting the number of live trees
You choose what stays mounted. A simple policy is to keep only the most recently used screens alive. Screens that fall out of the list are unmounted, so they lose state and release memory.
import { Activity, useState } from 'react';
const PAGES = ['a', 'b', 'c', 'd', 'e'];
const MAX_ALIVE = 3;
function Page({ id }) {
const [note, setNote] = useState('');
return (
<textarea
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder={`Notes for page ${id}`}
/>
);
}
export default function Pages() {
const [current, setCurrent] = useState('a');
const [recent, setRecent] = useState(['a']);
function open(id) {
setCurrent(id);
setRecent((prev) => [id, ...prev.filter((p) => p !== id)].slice(0, MAX_ALIVE));
}
return (
<>
{PAGES.map((id) => (
<button key={id} onClick={() => open(id)}>
{id}
</button>
))}
{recent.map((id) => (
<Activity key={id} mode={id === current ? 'visible' : 'hidden'}>
<Page id={id} />
</Activity>
))}
</>
);
}Open pages a, b, and c and type a note in each. All three keep their text. Open page d and page a drops out of recent. It unmounts, and its note is gone when you return. The key on each Activity keeps React matching the right tree as the list reorders.
Other ways to reduce the cost
- Keep state small. Store IDs and let a shared cache hold large data, so one copy serves many screens.
- Narrow context. Split frequently changing context from stable context, so hidden trees do not re-render for values they rarely need.
- Memoize expensive children with
memowhere profiling shows hidden re-renders are costly. - Do not mount boundaries you may never open. Pre-rendering is useful for a likely next screen, not for every possible one.
- Reset on purpose. Changing the
keyon a boundary discards its state when stale data would be worse than lost input.
Measure before deciding
Use the React DevTools Profiler to see whether hidden trees re-render, and your browser's memory tools to compare heap size with one tab alive and with ten. Decide from those numbers rather than from guesses. A few small hidden trees are usually fine. Many large ones that react to frequent updates are the case to worry about.
Exercise
A dashboard has 12 tabs, each wrapped in its own Activity. Users report the page feels heavy, and the Profiler shows hidden tabs re-rendering whenever a shared live-data context updates. Name two changes that would reduce the cost, and say what each one trades away.
Show answer
First, keep only recently used tabs alive, as in the MAX_ALIVE example, and unmount the rest. This frees memory and stops their re-renders, but an unmounted tab loses its state when the user returns. Second, narrow the live-data context, or have hidden tabs read it through a selector, so they do not re-render on every update. This reduces render work but adds code, and hidden tabs may show slightly stale data. Memoizing the expensive children inside each tab is also an acceptable second change.