Sub topic 6
Writing Effects that survive hide and show
This chapter assumes you know useState and useEffect, including cleanup functions and dependency arrays. It also assumes you have read the earlier chapters on the Activity component and its mode prop. You need React 19.2 or later.
The rule: every Effect must be able to stop
When an Activity boundary switches to hidden, React keeps the component's state and DOM but runs the cleanup function of every Effect inside it. When the boundary becomes visible again, React runs the Effects' setup functions again. The component is not remounted, so state keeps its old values.
Effects now follow the visibility of the screen, not only the lifetime of the component. The practical rule is that setup and cleanup must be a matched pair. Whatever setup starts, cleanup must stop, and running setup a second time must be safe.
An Effect that has no cleanup is the usual source of bugs. It keeps running while the screen is hidden, and it starts a second copy of itself when the screen is shown again.
Timers: stop on hide, resync on show
Here is the clock from the plan, with one change.
import { useEffect, useState } from 'react';
function Clock() {
const [now, setNow] = useState(() => new Date());
useEffect(() => {
setNow(new Date()); // resync: the saved state may be minutes old
const id = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(id);
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}The cleanup clears the interval, so nothing ticks while the panel is hidden. The extra setNow(new Date()) at the top of the Effect matters because of what Activity preserves. The now state still holds the time from when the panel was hidden. Without the resync, the user would see a stale time for up to one second after reopening the panel.
This pattern applies whenever an Effect keeps state up to date from an outside source. State survives hiding, but the outside world keeps changing. On setup, read the current value of the outside source once, then start listening for changes.
Subscriptions: listen only while visible
Browser events, WebSockets, and store subscriptions follow the same pairing.
import { useEffect, useState } from 'react';
export function OnlineBadge() {
const [online, setOnline] = useState(() => navigator.onLine);
useEffect(() => {
const update = () => setOnline(navigator.onLine);
update(); // catch changes that happened while hidden
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return <span>{online ? 'Online' : 'Offline'}</span>;
}The handler is defined inside the Effect, so removeEventListener receives the same function object that addEventListener received. If you passed a new inline function to each call, the listener would never be removed. Hidden screens would keep reacting to events, and every show would add one more listener.
The same applies to a chat connection. Setup calls connect() and cleanup calls disconnect(). A hidden chat room then holds no open socket. When the user returns, the room reconnects, and the messages already in state are still on screen while it does.
Fetching: abort on hide, refresh on show
A request that is in flight when the panel is hidden should not write its result into state later, or at least should be cancelled. AbortController handles both.
import { useEffect, useState } from 'react';
export function MessageList({ folder }) {
const [messages, setMessages] = useState(null);
useEffect(() => {
const controller = new AbortController();
fetch(`/api/messages?folder=${encodeURIComponent(folder)}`, {
signal: controller.signal,
})
.then((res) => res.json())
.then(setMessages)
.catch((err) => {
if (err.name !== 'AbortError') console.error(err);
});
return () => controller.abort();
}, [folder]);
if (messages === null) return <p>Loading...</p>;
return (
<ul>
{messages.map((m) => (
<li key={m.id}>{m.subject}</li>
))}
</ul>
);
}Each time the panel is shown, the Effect runs again, so the list is refreshed. The old messages value stays in state, so the user sees the previous list immediately instead of a loading message. The new data replaces it when it arrives. This is a stale-while-refresh behavior that you get without writing any extra code.
If you do not want a refetch on every show, Effects are the wrong place for the fetch. Use a data library that caches by key, or lift the data into a parent component. The Effect re-runs on show no matter what your dependency array says.
Restore what you changed
Not every side effect is a subscription. Some Effects change a shared global, such as the document title.
import { useEffect } from 'react';
export function useDocumentTitle(title) {
useEffect(() => {
const previous = document.title;
document.title = title;
return () => {
document.title = previous;
};
}, [title]);
}Suppose Inbox and Settings both call this hook and both stay mounted inside Activity boundaries. Without the cleanup, the title would belong to whichever panel ran its Effect last. With the cleanup, hiding a panel puts the old title back, and showing the other panel sets its own.
Cleanup should undo the setup, not reset to a fixed default. Saving previous and restoring it works even when the value was set by someone else.
Effects that run once per show
An Effect with an empty dependency array normally runs once per mount. Inside Activity it runs once per time the boundary becomes visible. That has consequences for Effects that report or log something.
useEffect(() => {
logPageView('settings');
}, []);This logs a page view each time the user opens the Settings tab. That may be what you want, because the user did look at the page again. If you want exactly one log per mount, track it with a useRef flag, or move the logging to the code that handles the tab click. Decide on purpose instead of finding out from a dashboard.
Avoid the reverse mistake as well. Do not write an Effect whose setup resets state, such as setText(''), unless you want hiding a panel to wipe it. That would undo the state preservation you added Activity to get.
Test the pairing with Strict Mode
You do not have to hide and show a panel by hand to find missing cleanup. In development, Strict Mode runs each Effect's setup, then its cleanup, then its setup again right after mount. This exercises the same setup, cleanup, setup sequence that Activity produces. If an Effect passes under Strict Mode, it will usually survive hide and show.
Look for these symptoms:
- Two intervals running, shown as a counter that increases twice per second.
- A request or socket opened twice.
- A console warning or error about a request that was never cancelled.
- A global value, such as the title, that does not return to its old value.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Timer keeps running while the panel is hidden | `setInterval` with no cleanup | Return `() => clearInterval(id)` |
| Event handler fires from a hidden panel | Listener never removed | Define the handler in the Effect, remove the same function in cleanup |
| Stale value flashes after reopening | State was saved, outside source changed | Read the current value at the start of setup |
| Counters double after each show | Setup adds a listener or subscription that cleanup does not remove | Make cleanup the exact inverse of setup |
| Panel state resets when shown | Setup calls a state setter with an initial value | Remove the reset, or reset on purpose in an event handler |
| Old response overwrites new data | Request not cancelled | Use `AbortController`, or an `ignore` flag set in cleanup |
Checklist for a new Effect
- Name what setup starts: a timer, listener, connection, request, or global change.
- Write cleanup that stops exactly that, using the same references.
- On setup, read any outside value once so state is not stale after a show.
- Ask whether it is acceptable for setup to run on every show. If not, move the work out of the Effect.
- Run the component under Strict Mode and look for doubled work.
Exercise
A PriceTicker component subscribes to a price feed with feed.subscribe(onPrice) inside useEffect and stores the latest price in state. It has no cleanup function. The component sits inside an Activity boundary that the user hides and shows. Name two problems this causes and write the corrected Effect. Assume feed.subscribe returns nothing, feed.unsubscribe(onPrice) removes a handler, and feed.current() returns the latest price.
Show answer
Problems: while hidden, the handler keeps running and updating state for a screen nobody can see, and each time the panel is shown, setup adds another subscription, so the handler runs more than once per price update. Also, the saved price is stale after reopening. Corrected Effect: useEffect(() => { const onPrice = (price) => setPrice(price); setPrice(feed.current()); feed.subscribe(onPrice); return () => feed.unsubscribe(onPrice); }, []); The handler is defined inside the Effect so cleanup removes the same function. The call to feed.current() resyncs the saved state on show.
Exercise
A Settings panel has this Effect: useEffect(() => { setName(''); fetchProfile().then((p) => setName(p.name)); }, []);. It sits inside Activity. A user types a new name, switches tabs, and switches back. What do they see, and how do you fix it so the typed text is kept?
Show answer
When the panel is shown again, setup runs again. It clears the name and refetches the saved profile, so the user's unsaved text is lost and replaced by the stored name. To keep it, do not reset or overwrite state inside the Effect on every show. Either load the profile once, for example by initializing from a parent or a cache, or skip the fetch when the field has been edited. Also add an AbortController to cancel the request in cleanup.