Sub topic 6
Writing Effects that survive hide and show
This chapter assumes you know useState, useEffect and cleanup functions. It also assumes you use React 19.2 or later, where Activity is available. The previous chapter showed that a hidden Activity boundary keeps state and DOM. Effects behave differently.
What React does to Effects
When mode changes to 'hidden', React runs the cleanup function of every Effect inside the boundary. State and DOM nodes stay. When mode returns to 'visible', React runs the Effect setup functions again.
For Effects, hiding works like unmounting. For state, it does not. Your component ends up with old state and freshly started Effects.
Write setup and cleanup as a pair
The rule is the same one you already use for Effects: every setup needs a cleanup that fully undoes it. Activity makes this rule easy to see, because hide and show repeat the cycle many times.
This clock stops ticking while hidden:
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 cleanup clears the interval, so no timer runs in the background. When the boundary becomes visible, the Effect creates a new interval.
Refresh stale state in setup
The clock has a flaw. now is kept while hidden, so after a long time hidden the clock shows the old time for up to one second. Setup should bring state up to date as well as start the timer:
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>;
}The same applies to any data the Effect keeps in sync with the outside world. A subscription to a store or socket should read the current value when it starts, because updates were missed while it was stopped.
import { 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>Width: {width}px</p>;
}If the window was resized while the panel was hidden, update() corrects the value as soon as the panel is shown.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Effect starts a timer or listener with no cleanup | It keeps running while the panel is hidden | Return a cleanup that stops it |
| Setup assumes state is fresh | Old state is shown until the next event arrives | Read the current value inside setup |
| Effect sends a "viewed" event | The event fires on every reveal, not just the first | Decide if this is wanted. If not, guard it with a ref |
| Cleanup is incomplete | Work from the first setup piles up with later runs | Make cleanup the exact reverse of setup |
Test the pair
Check each Effect by asking: "If React stopped this and started it again, would the component still be correct?" This is the same question Strict Mode asks in development. It re-runs setup and cleanup once on mount. An Effect that passes the Strict Mode check usually handles Activity too, but Activity repeats the cycle for as long as the app is open. Run both checks.
You can also watch the cycle directly:
import { Activity, useEffect, useState } from 'react';
function Probe() {
useEffect(() => {
console.log('setup');
return () => console.log('cleanup');
}, []);
return <p>Probe</p>;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<>
<button onClick={() => setShow(!show)}>Toggle</button>
<Activity mode={show ? 'visible' : 'hidden'}>
<Probe />
</Activity>
</>
);
}Each click on the button logs one cleanup or one setup. In development, the first mount logs the extra Strict Mode pair.
Cleanup is not for DOM side effects
Cleanup stops what your code started. It does not hide or pause things the browser owns. A <video> element stays in the page while hidden, so it keeps playing unless a cleanup pauses it. The next chapter covers that case.
Exercise
A hidden panel contains a component that opens a WebSocket in useEffect and closes it in the cleanup. It stores incoming messages in state. After the panel has been hidden for a minute and is shown again, what happens to the socket, the stored messages, and the messages sent during that minute?
Show answer
The cleanup closes the socket when the panel is hidden, and setup opens a new one when it is shown. The stored messages stay because state is preserved. Messages sent during the minute are missed unless setup fetches the current data or asks the server to replay what was missed.