Sub topic 2
What Stays: State and DOM While Hidden
This chapter assumes you know React function components, JSX, useState, useEffect, and the difference between mounting and unmounting. It also assumes React 19.2 or later, which provides Activity.
Conditional rendering removes a component when its condition becomes false:
{showDraft && <Draft />}React unmounts Draft. Its state resets, and its DOM nodes are removed. Showing it again mounts a new instance.
Activity hides a component without discarding its state or DOM:
<Activity mode={showDraft ? 'visible' : 'hidden'}>
<Draft />
</Activity>When the mode changes to hidden, React preserves the component instance. Text in an input, selected values, and useState values remain available. The DOM stays associated with the component, but React hides the Activity content from the user.
flowchart TD
A[Activity visible] -->|mode becomes hidden| B[State and DOM preserved]
B -->|mode becomes visible| C[UI appears with previous values]What Goes: Effects Are Cleaned Up
Activity treats visibility as a lifecycle boundary for Effects. When an Activity becomes hidden, React runs each Effect's cleanup function. When it becomes visible again, React runs the Effect setup again.
This lets a hidden screen stop subscriptions and timers while retaining its state:
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>;
}The Clock state survives hiding. The interval does not run while the Activity is hidden. It starts again when the Activity becomes visible.
Writing Effects That Survive Hide and Show
Write every Effect as a complete setup-and-cleanup pair. Release exactly what setup acquired: unsubscribe from subscriptions, clear timers, remove event listeners, and disconnect observers.
Do not assume that hiding automatically stops browser behavior. A video element can remain in the DOM, so pause it during cleanup:
useEffect(() => {
const video = videoRef.current;
return () => {
video.pause();
};
}, []);Use Activity when reopening a screen should restore its working state. Use conditional rendering when the screen should reset, or when keeping its DOM and state would waste memory.
Exercise
A hidden Activity contains a search input and a subscription. What should you expect when it becomes hidden?
Show answer
The input's state and DOM are preserved, but the subscription's Effect cleanup runs. When the Activity becomes visible, the Effect subscribes again.