Sub topic 8
Pre-rendering content the user may open next
This chapter covers what happens when an Activity boundary is hidden on its first render. React then prepares that content in the background before anyone asks for it.
Prerequisites
This chapter assumes you have read the earlier chapters on Activity and its mode prop. You should know how visible and hidden differ and that hiding cleans up Effects. You should also be comfortable with Suspense and React.lazy. If you have used use(promise), the data example will be familiar. If not, the explanation below is enough to follow along. All examples need React 19.2 or later.
The idea: work before the click
In the earlier chapters, you hid something the user had already seen. The boundary was visible first, then hidden, and React kept its state.
A second case is a boundary that is hidden from its very first render. The user has never seen it, but you expect they might open it soon. React still renders that content, at lower priority than the visible UI, and it does not run the content's Effects. So the content can load code and data before the user clicks. When the boundary becomes visible, the content is often ready and appears with little or no loading delay.
You don't call a special API for this. You write mode="hidden" on a boundary that has not been visible yet.
<Activity mode="hidden">
<ReportsPanel />
</Activity>React treats this as an instruction to prepare ReportsPanel without showing it.
What React does with a hidden first render
The same hidden boundary behaves differently from a visible one in these ways:
| Aspect | Hidden on first render | Visible |
|---|---|---|
| Component render functions | Run, at lower priority | Run at normal priority |
| DOM nodes | Created, but hidden from the user | Created and shown |
| State initializers (`useState(() => ...)`) | Run | Run |
| Effects (`useEffect`, `useLayoutEffect`) | Not mounted | Mounted |
| Suspense-enabled data and `lazy` code | Requested | Requested |
| Data fetching inside Effects | Does not start | Starts |
Two rows deserve attention. First, render functions run, so any code in the render path executes during pre-rendering. Second, Effects do not run. Anything you start inside an Effect waits until the boundary becomes visible.
The following diagram shows the lifecycle of a boundary that begins hidden.
Which data loads during pre-rendering
Pre-rendering helps only with work that happens during rendering. React can see two kinds of such work:
- Code splitting with
lazy. When React renders alazycomponent, it requests the module. Pre-rendering therefore downloads the JavaScript chunk. - Suspense-enabled data sources. These are sources that suspend during render, for example by calling
use(promise), or data libraries and frameworks that integrate with Suspense.
Data you fetch in useEffect is not loaded, because Effects don't run while the boundary is hidden. This is the most common reason pre-rendering seems not to work.
A complete example
The first file is a panel that reads data with use. A module-level cache makes sure the same promise is reused across renders. Without the cache, each render would create a new fetch and suspend again.
// Reports.jsx
import { use } from 'react';
const cache = new Map();
function loadReport(id) {
if (!cache.has(id)) {
cache.set(
id,
fetch(`/api/reports/${id}`).then((response) => response.json())
);
}
return cache.get(id);
}
export default function Reports() {
const report = use(loadReport('latest'));
return <pre>{JSON.stringify(report, null, 2)}</pre>;
}The app loads Reports lazily and wraps it in its own Activity and Suspense boundary. The Home tab is visible at first, and the Reports tab starts hidden.
// App.jsx
import { Activity, Suspense, lazy, useState } from 'react';
const Reports = lazy(() => import('./Reports'));
function Home() {
return <p>Welcome back.</p>;
}
export default function App() {
const [tab, setTab] = useState('home');
return (
<>
<button onClick={() => setTab('home')}>Home</button>
<button onClick={() => setTab('reports')}>Reports</button>
<Activity mode={tab === 'home' ? 'visible' : 'hidden'}>
<Home />
</Activity>
<Activity mode={tab === 'reports' ? 'visible' : 'hidden'}>
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
</Activity>
</>
);
}On the first render, the Reports boundary is hidden. After the visible Home content is ready, React renders Reports in the background. That request downloads the Reports chunk and starts the report fetch. If the user clicks the Reports tab a few seconds later, the chunk and the data are likely already there.
If the user clicks before the work finishes, nothing breaks. React treats the content as visible and gives it normal priority. The Suspense fallback may show for the remaining time, as it would without pre-rendering. Pre-rendering is an optimization and never changes what your app does.
The same panel with an Effect
Compare this version of the panel, which fetches in an Effect:
import { useEffect, useState } from 'react';
export default function ReportsWithEffect() {
const [report, setReport] = useState(null);
useEffect(() => {
let ignore = false;
fetch('/api/reports/latest')
.then((response) => response.json())
.then((data) => {
if (!ignore) setReport(data);
});
return () => {
ignore = true;
};
}, []);
if (report === null) return <p>Loading reports...</p>;
return <pre>{JSON.stringify(report, null, 2)}</pre>;
}Inside a boundary that starts hidden, this component renders its loading text and stops. The Effect has not run, so no request is sent. The request begins only after the user opens the tab. The component is correct, and it fetches at the right time for an Effect. It just gets no benefit from pre-rendering.
Pre-rendering and state
Pre-rendering creates the component's state the same way a visible render does. The initial values from useState are set, and any lazy initializer functions run. When the boundary becomes visible, that same state is used, so the component does not start over. If the user typed into an input after opening the panel and then hid it, that text is still there, as in earlier chapters.
The render-phase work also runs for components in the hidden tree, so render functions should stay pure. A component that writes to a global variable or reads Date.now() for a one-time decision during render is more likely to cause trouble. React may render it earlier than the user sees it, and render functions may run more than once.
Edge cases
Pre-rendering needs a hidden first render
The preparation happens when the boundary first appears. Compare these two ways of writing a tab:
// Pre-renders: the Activity boundary exists from the start, hidden.
<Activity mode={tab === 'reports' ? 'visible' : 'hidden'}>
<Reports />
</Activity>
// Does not pre-render: the boundary does not exist until the tab is chosen.
{tab === 'reports' && (
<Activity mode="visible">
<Reports />
</Activity>
)}In the second version, the Activity is mounted only when the condition is true, so no hidden render ever happens. Drive mode from state and keep the boundary in the tree.
Hiding after showing is not pre-rendering
If the boundary was visible and then becomes hidden, React keeps the existing state and DOM and cleans up Effects. That is state preservation, covered earlier. Pre-rendering is the case of a never-shown boundary being prepared.
Hidden content is not something the user can use
Hidden content is kept out of view, so users cannot interact with it. Treat pre-rendered content as invisible to users and screen readers. Don't rely on it for anything the user must see right away.
Prepared work can be wasted
Users do not always open what you prepared. If they never click Reports, you have spent bandwidth and CPU for nothing. React runs this work at lower priority, so it should not delay visible updates much. It still takes network capacity, memory, and device battery. A later chapter on cost covers this trade-off in more detail.
Data can become stale
A fetch that ran during pre-rendering finishes at that moment. If the user opens the panel an hour later, the data may be out of date. Pre-rendering does not refresh it. If freshness matters, your data layer needs its own revalidation, such as a cache that expires or a refetch when the panel becomes visible.
When to start a boundary hidden
Pre-rendering fits when all of these hold:
- The user is likely to open the content soon, such as the next tab, the next step of a wizard, or a page linked from the current one.
- Loading it takes noticeable time, because of a code chunk, a data request, or an expensive first render.
- The data source works during render (
lazy,use, or a Suspense-aware library). - The extra work is acceptable for the cost.
It is a poor fit when the content is rarely visited, when the data changes quickly, or when most users won't reach it. In those cases, rendering it only on demand is simpler.
Quick reference
- A boundary hidden on first render is pre-rendered at lower priority, without Effects.
lazycode and Suspense-enabled data load during pre-rendering. Data requested in Effects does not.- Keep the
Activityboundary in the tree and drivemodefrom state. - Render functions must be pure, since they run before the user sees the content.
- Pre-rendered data can go stale and can cost resources if the user never opens the content.
Exercise
A settings page is wrapped in <Activity mode="hidden"> from the first render. It fetches the user's profile inside a useEffect, and the page also uses lazy to load a heavy chart component. When the user later opens the page, which of these have already happened, and which have not? What single change would let the profile load ahead of time as well?
Show answer
The lazy chart module has already been requested, because pre-rendering renders the children and React loads lazy code during render. The profile fetch has not started, because Effects do not run while the boundary is hidden, so it begins only when the user opens the page. To load the profile early, replace the Effect-based fetch with a Suspense-enabled source, for example use(profilePromise) with a cached promise, so the request is made during render.
Exercise
A developer writes {tab === 'reports' && <Activity mode="visible"><Reports /></Activity>} and expects the Reports tab to be pre-rendered. Why does it not work, and how should the code change?
Show answer
The Activity boundary is not mounted until tab equals 'reports', so there is never a hidden first render and nothing is prepared in advance. Keep the boundary always in the tree and switch its mode instead: <Activity mode={tab === 'reports' ? 'visible' : 'hidden'}><Reports /></Activity>.