Sub topic 1
Preserving Hidden UI State with the React Activity Component
Prerequisites
This chapter assumes you understand React function components, JSX, props, useState, and basic mounting and unmounting. You also need React 19.2 or later, which includes Activity.
The problem: conditional rendering throws state away
Conditional rendering means showing a component only when a condition is true. When the condition becomes false, React removes the component from the tree. This is called unmounting.
Unmounting removes the component's DOM nodes and state. Showing the component again mounts a new instance with its initial 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>
{showDraft && <Draft />}
</>
);
}If you type text, hide the draft, and show it again, the textarea is empty. The Draft instance was destroyed.
Meet Activity
Activity lets React keep a subtree mounted while controlling whether it is visible or hidden. A subtree is a component and everything rendered below it.
The mode prop accepts either "visible" or "hidden":
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>
</>
);
}Switching between visible and hidden
When the mode changes to "hidden", React preserves the component's state and DOM, but the user cannot see the content. When it changes back to "visible", the existing subtree appears with its previous state.
Activity is useful for tabs, drawers, and screens where users expect unfinished input to remain.
Exercise
Why does a conditionally rendered textarea lose its text, while a textarea inside hidden Activity can keep it?
Show answer
Conditional rendering unmounts the component and discards its state. Activity hides the subtree while preserving its state and DOM.