Sub topic 11
Activity or something else? A decision guide
This chapter assumes you are comfortable with React function components, useState, and useEffect with cleanup functions. It also assumes you use React 19.2 or later, which includes Activity. Earlier chapters covered how Activity keeps state, how Effects are cleaned up when it is hidden, and what it costs. Here you will use that knowledge to choose between four options: Activity, conditional rendering, CSS hiding, and lifting state up.
The four options
Each option answers the question "what happens to this part of the UI when the user cannot see it?" in a different way.
- Conditional rendering (
{show && <Panel />}) unmounts the component. State, DOM nodes, and Effects are all destroyed. Showing it again mounts a fresh copy. Activitykeeps the component's state and DOM. When hidden, React hides the DOM withdisplay: none, runs Effect cleanups, and renders updates at lower priority. When visible again, React runs the Effects again.- CSS hiding (
style={{ display: 'none' }}or a class) keeps the component fully mounted. React does not know it is hidden. Effects keep running, and updates keep their normal priority. - Lifting state up moves the data into a parent component, or into a store outside the tree. The child can then be unmounted without losing the data, because the data does not live in the child.
The table compares them on the points that usually decide the choice.
| Concern | Conditional rendering | `Activity` | CSS hiding | Lifting state up |
|---|---|---|---|---|
| Local state kept while hidden | No | Yes | Yes | Yes, for the lifted state only |
| DOM kept while hidden | No | Yes | Yes | No |
| Effects stop while hidden | Yes (unmounted) | Yes (cleanup runs) | No | Yes (unmounted) |
| Hidden updates are low priority | Not applicable | Yes | No | Not applicable |
| Memory cost while hidden | None | Component tree and DOM | Component tree and DOM | Only the lifted data |
| Can be pre-rendered before first show | No | Yes | Yes, but it competes with visible work | No |
A decision flow
Start with what you must preserve, then check the cost and the side effects.
The flow is a starting point. The sections below explain each branch.
When conditional rendering is still right
Conditional rendering is the default. It is the cheapest option in memory, and its behavior is the easiest to predict. Prefer it when:
- The user expects a fresh start. A dialog that opens a "create item" form should usually be empty each time.
- The content is large and rarely revisited, such as a long report or a settings page used once a month.
- The component holds data that becomes stale quickly. A search result list from five minutes ago is often worse than a new load.
- The component depends on resources you want released, such as a large canvas, a WebGL context, or a big in-memory dataset.
function Dialogs({ open }) {
// A fresh form each time the dialog opens is the desired behavior.
return open ? <CreateItemForm /> : null;
}Using Activity here would be a mistake. The form would show the previous attempt, and you would have to add reset logic that conditional rendering gives you for free.
When Activity is the right tool
Choose Activity when the user would be annoyed to lose their place, and the tree is not too heavy to keep.
Typical cases:
- Tabs and sidebars. A user types a filter in one tab, switches away, and comes back. The filter is still there.
- Multi-step flows with back navigation. Going back to step 2 should show what the user entered in step 2.
- Drafts. A half-written message in a panel that the user toggles open and closed.
- Next-screen preparation. You want to render a likely next screen before the user asks for it. Rendering it inside a hidden boundary prepares it at low priority, so it can appear quickly.
The basic pattern is the one from the tabs example. The same boolean drives the mode prop:
import { Activity, useState } from 'react';
function Draft() {
const [text, setText] = useState('');
return <textarea value={text} onChange={(e) => setText(e.target.value)} />;
}
export default function App() {
const [showDraft, setShowDraft] = useState(true);
return (
<>
<button onClick={() => setShowDraft(!showDraft)}>Toggle draft</button>
<Activity mode={showDraft ? 'visible' : 'hidden'}>
<Draft />
</Activity>
</>
);
}Activity only helps if your Effects are written to tolerate being cleaned up and run again. If an Effect starts a timer, a subscription, or a connection, its cleanup must stop it. Otherwise the hidden screen keeps doing work that nobody can see. A component that already passes React's development double-invoke check for Effects usually behaves correctly.
When CSS hiding is acceptable
CSS hiding keeps everything mounted and running. That is the problem and the benefit.
It is acceptable when:
- The component is tiny and has no Effects, so there is nothing to stop.
- You need the content to stay live while hidden. A background data feed that must keep updating a count, for example.
- The hidden element is plain markup that does not involve React state at all.
It is a poor choice when the hidden component has timers, subscriptions, or media. Those keep running because React has no signal to clean them up. Hidden updates also run at normal priority, so a heavy hidden component can slow down the part the user is using.
A practical rule is that if you reach for display: none on a React component with Effects, Activity is almost always the better tool.
When lifting state up is better
Sometimes only a small amount of data needs to survive, and keeping the whole tree is wasteful. Lifting state up solves this.
Suppose a long list view has a single piece of state worth keeping, the search text. The list itself can be rebuilt cheaply from that text.
import { useState } from 'react';
function ResultsPanel({ query, onQueryChange }) {
return (
<>
<input value={query} onChange={(e) => onQueryChange(e.target.value)} />
<ul>
{/* results derived from query */}
</ul>
</>
);
}
export default function App() {
const [showResults, setShowResults] = useState(true);
const [query, setQuery] = useState('');
return (
<>
<button onClick={() => setShowResults(!showResults)}>Toggle results</button>
{showResults && <ResultsPanel query={query} onQueryChange={setQuery} />}
</>
);
}The panel is unmounted when hidden, so it costs nothing in memory. The query survives because the parent owns it.
This approach has these advantages over Activity:
- Memory use is limited to the data you chose to keep.
- You can save the data beyond the lifetime of the page, for example in
localStorageor the URL. - The behavior is explicit. You can see exactly what is preserved.
It has these disadvantages:
- Only the state you lift is preserved. Scroll position, text selection, focus, and uncontrolled inputs are lost.
- Each piece of state you want to keep needs wiring through props or a store.
- The parent re-renders when the lifted state changes, which can matter in large trees.
Decision criteria in practice
When the choice is not obvious, work through these questions in order.
- Does the user lose meaningful work if the UI resets? If not, use conditional rendering.
- What exactly must be preserved? If it is one or two values, lift them. If it includes DOM details such as scroll position, or many pieces of nested state, use
Activity. - How heavy is the tree? A tree with thousands of nodes or large in-memory data costs memory and rendering time while hidden. Measure before keeping many of them alive.
- How many hidden boundaries can exist at once? Three tabs are fine. A hundred list rows, each in its own
Activity, is not. - Do the Effects clean up correctly? If a component has Effects that cannot be stopped safely, fix them first or avoid
Activityfor that component. - Does the content need to be ready before the user asks? If so,
Activitywith pre-rendering is the only option that prepares the tree without showing it.
Common mistakes
- Using
Activitywhere a reset was wanted. Users see stale input. Add akeyto a conditionally rendered component if you need a reset in other cases. - Wrapping everything in
Activityby default. Memory grows with each preserved tree, and hidden trees still do some rendering work. - Forgetting cleanup. A hidden screen with an uncleaned interval or subscription keeps working. Media is the usual surprise, because the DOM node stays in the page, so a
videokeeps playing until a cleanup pauses it. - Expecting hidden trees to be free. They are lower priority, not free.
- Assuming a hidden component has no DOM. Its DOM nodes remain in the page, hidden from view. Code that queries the document can still find them.
Combining approaches
The options are not exclusive. A common arrangement is:
Activityaround the main tabs of an app, so each tab keeps its state.- Conditional rendering inside each tab for dialogs and one-off forms.
- A lifted store for data that must survive a page reload.
import { Activity, useState } from 'react';
function Inbox() {
const [filter, setFilter] = useState('');
const [composing, setComposing] = useState(false);
return (
<>
<input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter" />
<button onClick={() => setComposing(true)}>Compose</button>
{composing && (
<form onSubmit={(e) => { e.preventDefault(); setComposing(false); }}>
<textarea />
<button type="submit">Send</button>
</form>
)}
</>
);
}
function Settings() {
const [name, setName] = useState('');
return <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />;
}
export default function App() {
const [tab, setTab] = useState('inbox');
return (
<>
<button onClick={() => setTab('inbox')}>Inbox</button>
<button onClick={() => setTab('settings')}>Settings</button>
<Activity mode={tab === 'inbox' ? 'visible' : 'hidden'}>
<Inbox />
</Activity>
<Activity mode={tab === 'settings' ? 'visible' : 'hidden'}>
<Settings />
</Activity>
</>
);
}Here the inbox filter survives a tab switch, because the tab sits inside Activity. The compose form is conditionally rendered, so it starts empty each time it opens. Each part uses the behavior that suits it.
Summary of trade-offs
- Conditional rendering is cheap and resets everything. Use it as the default.
Activitypreserves state and DOM and stops Effects, at the price of memory for each hidden tree.- CSS hiding preserves everything and stops nothing. Reserve it for simple, effect-free markup or content that must stay live.
- Lifting state up preserves only chosen data and lets the tree unmount. Use it when a small amount of state matters.
Exercise
A dashboard has a chart panel with a large in-memory dataset (about 200 MB) and a single "selected date range" state value. Users toggle the panel often and want their date range kept. Which option fits best, and why?
Show answer
Lift the date range state into the parent and use conditional rendering for the panel. Only the small date range value needs to survive. Keeping the whole tree with Activity would hold the 200 MB dataset in memory while hidden. Conditional rendering frees it, and the lifted value restores the user's selection when the panel returns.
Exercise
A "Messages" tab contains a draft textarea and a WebSocket subscription opened in useEffect with a cleanup that closes it. You want the draft kept when users switch tabs, and you do not want the socket open while the tab is hidden. Which option do you choose, and what happens to the socket?
Show answer
Use Activity around the tab. The draft state and textarea DOM are kept while hidden. When the tab becomes hidden, React runs the Effect cleanup, which closes the WebSocket. When the tab becomes visible again, React runs the Effect again, which reopens it. CSS hiding would keep the socket open, and conditional rendering would lose the draft.