Sub topic 3
Switching between visible and hidden
This chapter assumes you can write function components with useState and useEffect, including cleanup functions. It also assumes you use React 19.2 or later, the first version that exports Activity. The previous chapter introduced the component. Here you learn how to control it through its mode prop. You will also learn what React does at each switch and which mistakes to avoid.
The mode prop
Activity takes one prop that matters here, mode. It has two valid values:
| Value | Meaning |
|---|---|
| `'visible'` | The children render normally. Their Effects run. The user sees them. |
| `'hidden'` | The children are hidden from the user. Their Effects are cleaned up. State and DOM are kept. |
mode is optional and defaults to 'visible'. An Activity with no mode behaves like a plain fragment, so you can add the wrapper first and wire up the prop later.
import { Activity } from 'react';
<Activity mode="visible">
<Sidebar />
</Activity>The prop is a plain value, not a ref or a method call. You drive it from state, props, or anything else you can compute during render. Switching it is just a re-render of the parent with a different value.
A minimal switch
The smallest useful pattern uses one boolean. The same boolean that conditional rendering would use now picks the mode.
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>
</>
);
}Type something, click the button, then click it again. The text is still there. With {showDraft && <Draft />}, Draft would be unmounted on hide and would start from an empty string on show.
Compare the two approaches directly:
| Step | Conditional rendering | Activity |
|---|---|---|
| Hide | Component unmounts. State is destroyed. DOM is removed. | Component stays. State is kept. DOM is kept but hidden. |
| Show | Component mounts fresh with initial state. | The same instance becomes visible again with its old state. |
| Effects on hide | Cleanup runs because the component unmounts. | Cleanup runs, but the component is not unmounted. |
| Effects on show | Effects run as part of mounting. | Effects run again. |
What React does on each switch
An Activity boundary moves between two states. Switching modes never destroys the subtree.
When mode changes from 'visible' to 'hidden', React does three things:
- It runs the cleanup function of every Effect inside the boundary.
- It hides the boundary's DOM nodes. React does this with
display: none. - It keeps the component instances, their state, and their refs in memory.
When mode changes back to 'visible', React does the reverse:
- It shows the DOM nodes again.
- It re-runs the Effects inside the boundary, so setup code executes again.
- It re-renders with whatever state and props are current.
The key point is that hiding triggers Effect cleanup without unmounting. In ordinary React, cleanup means the component is going away. Under Activity, cleanup means the component is going out of sight. Effects written with a correct cleanup function handle both cases without changes.
Watching the lifecycle
You can observe the sequence yourself with a component that logs its Effect.
import { Activity, useEffect, useState } from 'react';
function Panel() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Panel Effect: setup');
return () => console.log('Panel Effect: cleanup');
}, []);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
export default function App() {
const [open, setOpen] = useState(true);
return (
<>
<button onClick={() => setOpen(!open)}>
{open ? 'Hide' : 'Show'} panel
</button>
<Activity mode={open ? 'visible' : 'hidden'}>
<Panel />
</Activity>
</>
);
}Click the panel button a few times, then hide the panel. The console prints Panel Effect: cleanup. Show it again. The console prints Panel Effect: setup, and the counter still shows the number you reached.
An Effect with an empty dependency array [] normally runs once per mount. Under Activity, it runs once per visible period. The empty array does not stop it from re-running after the boundary is shown again.
The same behavior applies to every Effect inside the boundary. That includes Effects in nested children, in custom Hooks, and in library components.
Driving mode from real state
A boolean works for one panel. For several panels, derive each mode from a single piece of state. The tab example below uses one string and gives each panel its own boundary.
import { Activity, 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>
<Activity mode={tab === 'inbox' ? 'visible' : 'hidden'}>
<Inbox />
</Activity>
<Activity mode={tab === 'settings' ? 'visible' : 'hidden'}>
<Settings />
</Activity>
</>
);
}Exactly one boundary is visible at a time. Each tab keeps its own typed text because each has its own instance that is never unmounted.
If you have many panels, a small helper keeps the JSX readable:
import { Activity } from 'react';
function Panel({ id, active, children }) {
return (
<Activity mode={id === active ? 'visible' : 'hidden'}>
{children}
</Activity>
);
}You then write <Panel id="inbox" active={tab}>...</Panel>. The wrapper only translates a comparison into a mode.
The first render can be hidden
You can render an Activity as 'hidden' from the very first render. React then renders the children but does not run their Effects. The children's state is initialized, and the DOM is built but not shown. In the tab example above, the Settings panel is in this situation on first load.
When the boundary first becomes visible, its Effects run for the first time. For the component, "hidden from the start" and "hidden after being visible" are almost the same. In both cases the Effects are not active. The difference is only whether they have run before.
A later chapter covers why this is useful for pre-rendering. For now, remember that a hidden boundary is not an empty one. Its components render, and their render functions execute.
Common mistakes
Passing a boolean
mode accepts the two strings, not true and false. This is a frequent slip when you convert from {show && ...}.
// Wrong: mode expects 'visible' or 'hidden'
<Activity mode={showDraft}>
<Draft />
</Activity>
// Right
<Activity mode={showDraft ? 'visible' : 'hidden'}>
<Draft />
</Activity>Assuming hidden means stopped
Hiding runs Effect cleanup. It does not stop everything. Code that is not inside an Effect with a cleanup keeps running or keeps its effects. Examples include a subscription started during render, a timer created in an event handler, and a media element that is already playing. A hidden <video> is still in the page, and its sound keeps playing. The later chapter on pitfalls covers this. For now, treat mode="hidden" as "cleanup runs", not as "nothing happens".
Expecting a fresh start
Users sometimes expect a form to reset after being hidden. It will not. The state lives on. If you want a fresh component when a value changes, give it a key, or use conditional rendering for that case. Activity is for the opposite goal.
Wrapping everything
Every hidden boundary keeps its tree in memory, and React still renders it at lower priority when its props or state change. Wrapping all your routes in Activity costs more than it saves. Use it where losing state would hurt the user, and consider the cost described in a later chapter.
Nesting and independence
Boundaries are independent of each other. A hidden Activity inside a visible one stays hidden. A visible Activity inside a hidden one is also effectively hidden, because its parent's DOM is hidden and its Effects were cleaned up with the parent's.
import { Activity, useState } from 'react';
function Chat() {
return <p>Chat panel</p>;
}
function Notes() {
return <p>Notes panel</p>;
}
export default function Workspace() {
const [open, setOpen] = useState(true);
const [showNotes, setShowNotes] = useState(true);
return (
<>
<button onClick={() => setOpen(!open)}>Toggle workspace</button>
<button onClick={() => setShowNotes(!showNotes)}>Toggle notes</button>
<Activity mode={open ? 'visible' : 'hidden'}>
<Chat />
<Activity mode={showNotes ? 'visible' : 'hidden'}>
<Notes />
</Activity>
</Activity>
</>
);
}When open is false, both panels are hidden, whatever showNotes says. When open becomes true again, Notes follows its own showNotes value. The inner boundary remembers its setting, so you do not need to coordinate the two.
Placement rules
- Put
Activityaround the part of the tree whose state you want to keep. Do not put it around the component that owns the state, because that component is outside the boundary and a state reset there still resets everything. - Do not rely on hiding to reset anything. The boundary keeps its children's state.
- Keep the
modeexpression cheap and based on state you already have. It runs on every render of the parent. - If a child component renders no DOM nodes, such as one that returns
null, there is nothing for React to hide. The Effect cleanup and state preservation still apply.
Summary of behavior
modetakes'visible'or'hidden', and defaults to'visible'.- Changing
modenever unmounts the children. - Going hidden cleans up Effects and hides DOM. Going visible runs Effects again.
- State, refs, and the DOM nodes survive both transitions.
- A boundary may start hidden. Its components render, but their Effects have not run yet.
Exercise
A component inside <Activity mode={show ? 'visible' : 'hidden'}> has useEffect(() => { console.log('setup'); return () => console.log('cleanup'); }, []). Starting with show as true, the user toggles it to false and then back to true. What does the console print in total, and what happens to the component's useState values?
Show answer
The console prints "setup" when the component first appears, "cleanup" when show becomes false, and "setup" again when show becomes true. (In development, Strict Mode may add extra setup/cleanup pairs at the first mount.) The useState values are never reset, because hiding only cleans up Effects and does not unmount the component.
Exercise
A teammate wrote <Activity mode={isOpen}> where isOpen is a boolean. What is wrong, and how do you fix it?
Show answer
mode accepts only the strings 'visible' and 'hidden', not a boolean. Change it to <Activity mode={isOpen ? 'visible' : 'hidden'}>.