Sub topic 1
The problem: conditional rendering throws state away
Every React app hides and shows parts of its UI. Tabs, sidebars, dialogs, wizards, and drawers all appear and disappear. The usual tool is conditional rendering, and it has a cost that is easy to miss: when a component stops being rendered, React destroys its state. This chapter explains the mechanism, shows where it hurts, and sets up the problem that the Activity component solves in later chapters.
Prerequisites
This chapter assumes you already know:
- React function components, props, and JSX.
useStateanduseEffect, including Effect cleanup functions.- The basic idea that React mounts a component when it first appears and unmounts it when it disappears.
- Access to React 19.2 or later if you want to run the later chapters'
Activityexamples. This chapter itself uses only features available in earlier versions.
You do not need to know anything about Activity yet.
What conditional rendering does
Conditional rendering means choosing in JSX whether a component is part of the output. The most common form is the && operator:
{showDraft && <Draft />}When showDraft is true, React renders <Draft />. When it becomes false, the expression evaluates to false, and React renders nothing in that position.
React tracks components by their position in the tree. If a component was at a position on the previous render and nothing is there on the next render, React unmounts it. Unmounting has three effects:
- React removes the component's DOM nodes from the page.
- React runs the cleanup function of every Effect in the component and its descendants.
- React discards the component's state, including every
useStateanduseReducervalue and everyuseRefobject.
When the condition turns true again, React mounts a brand new instance. It runs useState initializers again, creates new DOM nodes, and runs Effects from scratch. The new instance has no connection to the old one.
A worked example: the lost draft
Here is a small app with a text area inside a Draft component. A button toggles whether Draft is rendered.
import { 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>
{showDraft && <Draft />}
</>
);
}Try this sequence:
- Type "Dear team," into the text area.
- Click Toggle draft. The text area disappears.
- Click Toggle draft again. The text area returns, and it is empty.
The text lived in the text state variable inside Draft. When showDraft became false, React unmounted Draft and threw that variable away. The second Draft is a new instance whose useState('') starts from the empty string.
The state is not "hidden somewhere." It no longer exists.
Why React works this way
Destroying state on unmount is correct behavior, and it is the default for good reasons:
- Memory. A component that is not on screen holds no memory. In a large app with many screens, this matters.
- No stale work. An unmounted component runs no Effects, so it holds no subscriptions, timers, or network requests.
- Predictability. The UI is a function of the current state. If a component is not in the output, nothing about it remains.
The trade-off is that the state you wanted to keep gets removed along with everything else. React's rule is that state belongs to a component instance, and an instance lives only as long as it is rendered.
Where this hurts in real apps
Losing state is harmless for a toggle that shows a static message. It becomes a problem when the hidden UI holds something the user would be unhappy to lose.
- Unsaved form input. A user fills half a form, opens another tab, and returns to an empty form.
- Scroll position. A long list is scrolled to item 400. After switching away and back, it starts at the top.
- Filters and sort order. A table's filter text, selected column, and page number reset.
- Expanded sections and selections. An accordion or tree view collapses to its default.
- Local data. A component fetched data on mount. After remounting, it fetches again and shows a loading state.
- Focus and text selection. The element that held focus is a new element, so focus is lost.
The tab interface below is the typical case. Each tab has its own input, and each tab is shown through conditional rendering:
import { useState } from 'react';
function Inbox() {
const [filter, setFilter] = useState('');
return <input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter" />;
}
function Settings() {
const [name, setName] = useState('');
return <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name" />;
}
export default function Tabs() {
const [tab, setTab] = useState('inbox');
return (
<>
<button onClick={() => setTab('inbox')}>Inbox</button>
<button onClick={() => setTab('settings')}>Settings</button>
{tab === 'inbox' && <Inbox />}
{tab === 'settings' && <Settings />}
</>
);
}Type "invoices" into the Inbox filter, switch to Settings, and switch back. The filter is empty. Each click on a tab unmounts one panel and mounts the other, so neither panel can remember anything.
Effects are reset too
State is not the only thing lost. Effects follow the component's lifecycle, so unmounting runs cleanup and remounting runs setup again.
import { useEffect, useState } from 'react';
function Clock() {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id);
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}If Clock is rendered conditionally, hiding it clears the interval, and showing it creates a new one. That is the behavior you want here, because a hidden clock should not tick. The same mechanism that discards your text also stops your timers. Any approach that preserves state has to decide what happens to Effects. That is why the later chapters on Activity spend time on Effect cleanup.
Workarounds and their costs
Developers have long worked around state loss. Each workaround trades one problem for another.
| Workaround | How it works | Cost |
|---|---|---|
| Lift state up | Move `useState` into a parent that stays mounted, and pass values down as props | More props and more code in the parent. The DOM is still recreated, so scroll position and focus are lost |
| Store state elsewhere | Keep it in context, a state library, `localStorage`, or the URL | Extra infrastructure. You must decide what to store and when to clear it |
| Hide with CSS | Always render the component and toggle `display: none` | State and DOM survive, but Effects keep running while the component is hidden |
| Use the `key` prop to control identity | Change `key` to reset state deliberately | Does the opposite: it forces a reset, so it does not preserve anything |
Hiding with CSS
The CSS approach deserves a closer look because it is the most direct way to keep a component's state:
import { 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>
<div style={{ display: showDraft ? 'block' : 'none' }}>
<Draft />
</div>
</>
);
}The text now survives because Draft stays mounted. The costs are less obvious:
- Effects keep running. A hidden
Clockstill ticks every second and re-renders. A hidden component that polls a server keeps polling. A subscription stays open. - Rendering stays at full priority. When props or context change, React re-renders the hidden component at the same priority as visible UI. The work is wasted because nobody can see it.
- Side effects stay active. A playing
<video>under adisplay: noneparent keeps playing audio. - Initial cost. Everything renders up front, even tabs the user never opens.
So CSS hiding preserves state by giving up the cleanup that unmounting provides. You get one benefit of keeping the component alive and all of its downsides.
What a better tool would do
The two approaches sit at opposite ends. Conditional rendering cleans everything up and keeps nothing. CSS hiding keeps everything and cleans nothing. What the examples above call for is in between:
- Keep the component's state and its DOM nodes.
- Run Effect cleanup when the UI is hidden, so timers stop and subscriptions close.
- Run the Effects again when the UI becomes visible.
- Update hidden content at a lower priority than visible content.
This is the role of the Activity component in React 19.2. The following chapters introduce it, explain how its mode prop works, and show what it preserves and what it cleans up.
Common mistakes to watch for
- Assuming state persists because the component "is still in the code." State persists only while the instance is rendered. A conditional that returns
falseremoves the instance. - Expecting a position change to keep state. If you move a component to a different position in the tree, React sees an unmount and a mount. The state resets.
- Using CSS hiding and forgetting the Effects. A hidden component with an interval, a WebSocket, or a video still does that work. Check the network tab and CPU use after hiding something.
- Resetting by accident with
key. If akeychanges each render, for examplekey={Math.random()}, the component remounts every time and loses its state constantly.
Summary
- Conditional rendering unmounts a component when its condition is false. Unmounting destroys state, refs, and DOM nodes, and runs Effect cleanup.
- Re-showing the component creates a new instance with fresh state.
- Lifting state up, external stores, and CSS hiding each preserve some state but add code or keep Effects running.
- What is missing is a way to keep state and DOM while stopping Effects and lowering update priority.
Activityprovides that.
Exercise
A tab panel renders a long list with {tab === 'list' && <BigList />}. The user scrolls to item 400, switches to another tab, and returns. The list is back at the top. Explain why, and name one workaround that would keep the scroll position and one cost of that workaround.
Show answer
Switching tabs makes the condition false, so React unmounts BigList. That removes its DOM nodes, which hold the scroll position, and discards its state. Returning mounts a new instance that starts at the top. One workaround is to always render BigList and hide it with display: none. That keeps the DOM node and state, so the scroll position is typically kept, but any Effects in BigList, such as polling or subscriptions, keep running while it is hidden, and updates to it are rendered at full priority.
Exercise
A Clock component with a setInterval Effect is hidden with <div style={{ display: 'none' }}> instead of conditional rendering. What happens to the interval, and how does that differ from conditional rendering?
Show answer
The interval keeps running and calls setNow every second, because the component stays mounted and its Effect cleanup never runs. With conditional rendering, hiding unmounts the component, React runs the cleanup that calls clearInterval, and the timer stops.
Exercise
In the Tabs example that uses {tab === 'inbox' && <Inbox />}, a developer wants the Inbox filter text to survive tab switches without changing how tabs are rendered. Describe how lifting state up would do this, and name what would still be lost.
Show answer
Move the filter state into Tabs, which stays mounted, and pass filter and setFilter to Inbox as props. The text then survives because it lives in the parent. The Inbox DOM nodes are still destroyed and recreated, so scroll position, focus, and text selection inside Inbox are still lost.