Sub topic 7
Pitfalls: media playback and other DOM side effects
This chapter assumes you are comfortable with function components, useState, and useEffect with cleanup functions. It also assumes you have read the earlier chapters on what Activity keeps and what it cleans up. You need React 19.2 or later.
The gap in "Effects are cleaned up when hidden"
When an Activity boundary becomes hidden, React keeps the component's state and its DOM nodes. It also runs the cleanup functions of the Effects inside the boundary. The cleanup is what stops timers, subscriptions, and listeners.
That rule is easy to over-trust. React hides the DOM by applying display: none to the top-level DOM nodes inside the boundary. React does not know what a DOM node is doing internally. A <video> that is playing keeps playing when its parent gets display: none. An <audio> element does the same. The node is still in the document, so the browser still treats it as active.
The rule of thumb for this chapter:
- Anything React owns, such as state and Effects that you wrote, is handled by
Activity. - Anything the browser owns, such as playback position, a running animation, or an open dialog, stays as it was unless your cleanup stops it.
Reproducing the problem
Here is a tab panel with a video. Nothing in the component stops playback.
import { Activity, useState } from 'react';
function VideoPanel() {
return <video controls src="/clip.mp4" />;
}
export default function App() {
const [tab, setTab] = useState('video');
return (
<>
<button onClick={() => setTab('video')}>Video</button>
<button onClick={() => setTab('notes')}>Notes</button>
<Activity mode={tab === 'video' ? 'visible' : 'hidden'}>
<VideoPanel />
</Activity>
{tab === 'notes' && <p>Notes go here.</p>}
</>
);
}Press play, then click Notes. The video is no longer visible, but you can still hear it. With conditional rendering ({tab === 'video' && <VideoPanel />}) this would not happen, because unmounting removes the node and the browser stops the media. Activity keeps the node, so the audio continues.
Keeping the node is the point of Activity. When the user comes back, the playback position, volume, and scroll position inside the panel are all still there. The cost is that you must say what should happen to the media while the panel is hidden.
The fix: pause in a cleanup function
Because React runs Effect cleanup when the boundary is hidden, the cleanup is the right place to pause the media:
import { useLayoutEffect, useRef } from 'react';
function VideoPanel() {
const videoRef = useRef(null);
useLayoutEffect(() => {
const video = videoRef.current;
return () => {
video.pause();
};
}, []);
return <video controls ref={videoRef} src="/clip.mp4" />;
}Three details matter here.
- The Effect body does nothing. Only the cleanup is useful. That is normal for this pattern, and it is acceptable to have an Effect whose purpose is just to register a cleanup.
- The ref value is copied into a local variable (
video) when the Effect runs. By the time cleanup runs,videoRef.currentcould point somewhere else, so the local copy is safer. - The Effect is a layout Effect. The next section explains why.
Why `useLayoutEffect`
Cleanup for a normal useEffect is passive: React may run it a little after the browser has painted. For a hidden boundary that can mean the panel disappears and the audio keeps going for a short moment. A layout Effect cleanup runs synchronously during the commit, before the browser paints the hidden state. The pause and the hide therefore happen together.
For media, this difference is audible, so useLayoutEffect is the better fit. For timers and subscriptions, a plain useEffect is fine, because a brief delay is not visible.
What happens when the panel is shown again
When the boundary becomes visible, React runs the Effect body again. In the example above the body is empty, so the video stays paused at its current position. The user has to press play. That is usually the right default, because resuming audio automatically can surprise people and browsers often block autoplay without a user gesture.
If you do want playback to resume, record whether it was playing and restart it in the Effect body:
import { useLayoutEffect, useRef } from 'react';
function ResumableVideo() {
const videoRef = useRef(null);
const wasPlaying = useRef(false);
useLayoutEffect(() => {
const video = videoRef.current;
if (wasPlaying.current) {
video.play().catch(() => {
// The browser may refuse to play without a user gesture.
});
}
return () => {
wasPlaying.current = !video.paused;
video.pause();
};
}, []);
return <video controls ref={videoRef} src="/clip.mp4" />;
}The catch is required in practice. play() returns a promise, and the browser rejects it when autoplay policy blocks playback. Without the catch, you get an unhandled promise rejection.
The ref wasPlaying survives hiding, because refs belong to the component instance and Activity keeps that instance alive.
Other DOM side effects that outlive hiding
Media is the most obvious case, but the same reasoning applies to anything the browser tracks on a node that stays in the document.
| Side effect | Why it survives hiding | What to do in cleanup |
|---|---|---|
| `<video>` or `<audio>` playback | The element is still in the document | Call `pause()` |
| Web Animations or CSS animations driven from script | The animation object is attached to a live element | Call `pause()` or `cancel()` on the animation |
| Focus on an element inside the panel | Hidden elements lose focus visually in most browsers, but your own code may refocus them | Avoid calling `focus()` from code that runs while hidden |
| Open `<dialog>` opened with `showModal()` | The browser's top layer is not controlled by the parent's `display` | Call `close()` |
| Fullscreen or Picture-in-Picture state | Owned by the browser, not by the component | Exit fullscreen or PiP |
| Third-party widgets attached to a node (maps, charts, players) | The library keeps its own timers and listeners | Call the library's pause, stop, or destroy method |
The last row deserves attention. A map or chart library often starts its own requestAnimationFrame loop or ResizeObserver. React does not see that loop. If the library offers a way to pause or detach, do it in cleanup and reattach in the Effect body.
A dialog example
A modal dialog opened with showModal() is placed in the browser's top layer. Hiding the parent with display: none hides the dialog too, but the dialog still counts as open. Closing it in cleanup makes the state consistent:
import { useEffect, useRef, useState } from 'react';
function Confirm() {
const dialogRef = useRef(null);
const [open, setOpen] = useState(false);
useEffect(() => {
const dialog = dialogRef.current;
return () => {
if (dialog.open) {
dialog.close();
}
};
}, []);
return (
<>
<button onClick={() => { dialogRef.current.showModal(); setOpen(true); }}>
Delete
</button>
<dialog ref={dialogRef} onClose={() => setOpen(false)}>
<p>Delete this item?</p>
<form method="dialog">
<button>Cancel</button>
</form>
</dialog>
<p>{open ? 'Dialog open' : 'Dialog closed'}</p>
</>
);
}The onClose handler keeps the open state in sync when close() runs from cleanup, so the component's state still describes the dialog.
Finding these bugs
Side effects that outlive hiding do not throw errors. They show up as behavior the user notices: sound from a screen they cannot see, or a chart that burns CPU in a background tab. Some ways to catch them:
- Test each hidden state by hand. Start the media, an animation, or a widget, switch tabs, and check for sound and CPU use.
- Read the Effects in a component and ask, for each one, what the screen does that React does not know about.
- Use the browser's tab audio indicator and the performance panel to look for work that continues after hiding.
- Search your code for direct DOM calls such as
play(,showModal(,requestFullscreen(, andrequestAnimationFrame(. Each one needs a matching stop somewhere.
A related trap: DOM measurements while hidden
Elements inside a hidden boundary have display: none, so they have no layout. Calls like getBoundingClientRect() return zeros, and offsetHeight returns 0. If an Effect measures an element and stores the result in state, the stored value may be wrong when the Effect runs for a hidden tree.
Measure in an Effect whose body runs when the boundary becomes visible. Because React re-runs Effects on show, an Effect that measures in its body gets the correct values at that time. Avoid measuring in event handlers or timers that can fire while the panel is hidden.
Checklist for a screen inside Activity
- List every Effect and what it starts. Confirm each cleanup stops it.
- List every DOM API the component calls directly. Confirm each has a matching stop.
- Check third-party widgets for a pause or destroy method and call it in cleanup.
- Decide whether the screen should resume work when shown again, and write that in the Effect body.
- Use
useLayoutEffectwhen the stop must happen before the next paint, as with audio.
Exercise
A tab panel contains an <audio> element and uses <Activity mode={tab === 'music' ? 'visible' : 'hidden'}>. The user starts the music and switches to another tab, but the music keeps playing. Why does this happen, and how do you fix it?
Show answer
Activity keeps the audio element in the document and only hides it with display: none, so the browser keeps playing it. React does not stop playback because it does not know the element is playing. Fix it by adding an Effect, preferably useLayoutEffect, that copies audioRef.current to a local variable and returns a cleanup function that calls pause(). React runs that cleanup when the boundary becomes hidden.
Exercise
In the resumable video example, why is wasPlaying stored in a ref and not in state, and why does play() have a catch?
Show answer
Changing wasPlaying does not need to re-render anything, and the value is written inside a cleanup function, where setting state is unnecessary work. A ref keeps its value while the boundary is hidden because Activity preserves the component instance. play() returns a promise that the browser rejects when autoplay policy blocks playback, so the catch prevents an unhandled promise rejection.
Exercise
A hidden panel contains a chart library that runs its own requestAnimationFrame loop. CPU use stays high after you switch away. What should the component do?
Show answer
React cannot see the library's loop, so the component must stop it. Create the chart in an Effect and, in the cleanup, call the library's pause, stop, or destroy method. If the library supports pausing, recreate or resume it in the Effect body so it starts again when the panel is shown.