Sub topic 5
What goes: Effects are cleaned up when hidden
The previous chapter showed that Activity keeps a hidden component's state and DOM. This chapter covers the part that does not stay. When a boundary becomes hidden, React cleans up the Effects of everything inside it. When the boundary becomes visible again, React runs those Effects again.
Prerequisites
This chapter assumes you know the following:
useStateanduseEffect, including the cleanup function an Effect can return.- The idea of Effect setup and cleanup as a pair. Setup connects to something and cleanup disconnects from it.
- The
modeprop ofActivity('visible'or'hidden'), covered earlier in this tutorial. - React 19.2 or later, which exports
Activity.
Hidden is not unmounted, but Effects act as if it were
Conditional rendering ties everything to mounting. A mounted component has state, DOM, and active Effects. An unmounted component has none of them.
Activity splits that bundle in two:
- Kept while hidden: state, DOM nodes, and refs.
- Removed while hidden: Effects. React runs every cleanup function in the hidden subtree, for both
useEffectanduseLayoutEffect.
The reasoning is that a hidden screen should keep what the user typed and where they scrolled. It should not keep doing work the user cannot see. Timers, subscriptions, and event listeners are work, so React stops them.
The last transition is worth noticing. A component that is hidden has already had its cleanup run. When it is unmounted from that state, React has nothing left to clean up.
Watching the lifecycle
The quickest way to see this is to log setup and cleanup. This component logs both, and it holds a counter to show that state survives.
import { Activity, useEffect, useState } from 'react';
function Panel() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Panel: setup');
return () => console.log('Panel: cleanup');
}, []);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
export default function App() {
const [show, setShow] = useState(true);
return (
<>
<button onClick={() => setShow(!show)}>Toggle panel</button>
<Activity mode={show ? 'visible' : 'hidden'}>
<Panel />
</Activity>
</>
);
}Click the panel button a few times, then hide the panel. The console prints Panel: cleanup. Show it again. The console prints Panel: setup, and the counter still has its old value.
Compare this with {show && <Panel />}. That version prints the same two messages, but the counter resets to 0, because the component was destroyed and rebuilt.
The Effect has an empty dependency array, yet it still runs again. Dependencies decide when an Effect re-runs while the component is visible. Hiding and showing is a separate trigger that ignores them.
:::note In development, React Strict Mode also runs an extra setup and cleanup cycle when a component first mounts. You may see more log lines than the example above suggests. The pattern is the same: every setup is matched by a cleanup. :::
The note above is the intent. Here is the real callout.
A timer that stops while hidden
A clock is a common case. Without cleanup, an interval keeps firing after the user leaves the screen.
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>;
}Inside a hidden Activity, React runs clearInterval(id). No state updates arrive, and the browser does no work for this component. When the boundary becomes visible, React runs the Effect body again and starts a new interval.
You did not write anything Activity-specific. The Effect already pairs setup with cleanup, and that is the only requirement. An Effect written correctly for unmounting is also correct for hiding.
The stale value after showing
This clock has a small bug under Activity. State is kept while the boundary is hidden, so now still holds the time from when the user left. After showing, the old time appears until the first new tick, up to a second later.
With conditional rendering this never happened, because a remounted component ran its initializer again and got a fresh new Date(). Under Activity, the initializer runs once.
The fix is to resynchronize at the start of the Effect.
import { useEffect, useState } from 'react';
function Clock() {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
setNow(new Date());
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id);
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}Setup is now the one place that brings state up to date with the outside world. This is the main design rule of the chapter: any state that mirrors something external needs a refresh in setup, because the mirror was not updating while hidden.
Which things are affected
The table summarizes what happens to each part of a component while its Activity boundary is hidden.
| Part of the component | While hidden | When shown again |
|---|---|---|
| `useState` and `useReducer` values | Kept | Same values |
| DOM nodes | Kept in the page, hidden from view | Revealed, not rebuilt |
| Refs | Kept | Same objects |
| `useEffect` | Cleanup has run, Effect is not active | Setup runs again |
| `useLayoutEffect` | Cleanup has run, Effect is not active | Setup runs again |
| Browser work started by an Effect (timers, listeners, sockets you close in cleanup) | Stopped | Started again by setup |
| Work started outside an Effect (for example, a call in the render body or a module-level subscription) | Not touched by React | Not touched by React |
The last row matters. React can only undo what you registered through an Effect cleanup. It does not track a listener you attached at module load or a subscription started during rendering.
A subscription example
Here is a component that tracks the window width. It follows the same shape as the clock: resync first, subscribe second, unsubscribe in cleanup.
import { Activity, useEffect, useState } from 'react';
function WindowWidth() {
const [width, setWidth] = useState(() => window.innerWidth);
useEffect(() => {
const update = () => setWidth(window.innerWidth);
update();
window.addEventListener('resize', update);
return () => window.removeEventListener('resize', update);
}, []);
return <p>Window is {width}px wide</p>;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<>
<button onClick={() => setShow(!show)}>Toggle</button>
<Activity mode={show ? 'visible' : 'hidden'}>
<WindowWidth />
</Activity>
</>
);
}While the panel is hidden, the user can resize the window. No listener is attached, so width is stale. The call to update() at the start of setup fixes it the moment the panel returns.
Edge cases
Hidden on first render
If an Activity boundary starts with mode="hidden", its children render, but their Effects do not run. There is nothing to clean up because nothing was set up. The Effects run for the first time when the boundary first becomes visible. A later chapter uses this for pre-rendering.
Unmounting while hidden
If the whole Activity leaves the tree while hidden (a parent stops rendering it), React does not run cleanup a second time. The cleanup already ran when the boundary was hidden.
Cleanup that must be idempotent
React can run setup and cleanup many times over a component's lifetime. Each pair must leave the world as it found it. If cleanup closes a connection, setup must open a new one rather than assume the old one still exists. Avoid module-level flags like let connected = false that you set once and never reset.
Effects that fetch data
A fetch in an Effect with an empty dependency array runs again each time the boundary becomes visible. That can be what you want, since the data may be stale after a long absence. If it is not, keep the result in state and skip the request when it is already there. Abort in-flight requests in cleanup so a response does not arrive after the user has left.
import { useEffect, useState } from 'react';
function Feed() {
const [items, setItems] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch('/api/items', { signal: controller.signal })
.then((res) => res.json())
.then(setItems)
.catch((err) => {
if (err.name !== 'AbortError') throw err;
});
return () => controller.abort();
}, []);
if (items === null) return <p>Loading…</p>;
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}This version refetches on every show. Because items is kept in state, the old list stays on screen while the new request runs, and no loading flash appears.
Common errors
- Assuming the Effect runs only once. An empty dependency array means "no re-runs while visible." It does not protect against hide and show cycles. Code that must happen exactly once, such as sending an analytics event, belongs in an event handler or needs its own guard.
- Forgetting the cleanup. A missing
return () => ...was a leak on unmount before. UnderActivityit also means the work continues in the background for as long as the boundary stays hidden, which can be a long time. - Skipping the resync. Stale state after showing is the most common surprise. Ask of every Effect: what does this state mirror, and is it still correct on return?
- Blaming
Activityfor work it cannot see. Anything started outside an Effect keeps running. Move it into an Effect with a cleanup. - Expecting media to stop on its own. Hidden DOM stays in the page, so a playing video keeps playing. That is covered in the next chapters of this tutorial.
Exercise
A Ticker component keeps a seconds count in state and starts setInterval(() => setSeconds(s => s + 1), 1000) in an Effect with [] dependencies, returning () => clearInterval(id). It is wrapped in an Activity that is hidden for 30 seconds and then shown. What does the user see right after it is shown, and does the count include the 30 hidden seconds?
Show answer
The user sees the same seconds value as when it was hidden, because state is kept. The count does not include the hidden 30 seconds, because cleanup cleared the interval and no ticks ran. After showing, setup starts a new interval and the count continues from the old value. If you want elapsed wall-clock time instead, store a start timestamp and compute the difference during setup or render.
Exercise
A component adds a keydown listener to document inside a useEffect with no cleanup. It is placed in a hidden Activity. Does the listener keep firing while the boundary is hidden, and how do you fix it?
Show answer
Yes. React can only undo what a cleanup function undoes, so the listener stays attached and its handler keeps running while the content is hidden. Fix it by returning a cleanup function that calls document.removeEventListener('keydown', handler) with the same handler reference. Then hiding the boundary detaches the listener and showing it attaches a new one.