Sub topic 7
Pitfalls: media playback and other DOM side effects
This chapter assumes you know useState, useEffect cleanup functions, and the Activity mode prop from the earlier chapters. It covers a case where Activity's behavior surprises people: DOM elements that keep doing something after they are hidden.
Hidden does not mean stopped
When an Activity boundary becomes hidden, React does two things:
- It cleans up the Effects inside the boundary.
- It hides the DOM nodes, using
display: none, and keeps them in the page.
React cannot know what a DOM node is doing on its own. A <video> or <audio> element keeps playing when it is hidden. The same applies to an iframe that runs its own scripts. React cleans up your Effects, but it never reaches into the browser to stop the element.
import { Activity, useState } from 'react';
function VideoPanel() {
return <video controls src="/clip.mp4" />;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<>
<button onClick={() => setShow(!show)}>Toggle video</button>
<Activity mode={show ? 'visible' : 'hidden'}>
<VideoPanel />
</Activity>
</>
);
}Start the video, then click the button. The video disappears, but you can still hear its sound. With plain conditional rendering ({show && <VideoPanel />}) this problem never appeared, because unmounting removed the element and the browser stopped playback.
Stop playback in an Effect cleanup
The fix uses what you already know. Hiding an Activity runs your Effect cleanups, so put the "stop" code there.
import { Activity, useLayoutEffect, useRef, useState } from 'react';
function VideoPanel() {
const videoRef = useRef(null);
useLayoutEffect(() => {
const video = videoRef.current;
return () => {
video.pause();
};
}, []);
return <video ref={videoRef} controls src="/clip.mp4" />;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<>
<button onClick={() => setShow(!show)}>Toggle video</button>
<Activity mode={show ? 'visible' : 'hidden'}>
<VideoPanel />
</Activity>
</>
);
}Three details matter here:
- The Effect has an empty dependency array. It sets up when the boundary is visible and cleans up when it becomes hidden. When the boundary is visible again, React runs the Effect again.
- The Effect copies
videoRef.currentinto a local variable before returning the cleanup. The cleanup then uses a stable reference to the element. - The Effect has no setup work, only a cleanup. That is intentional. The Effect exists to give React a function to call at hide time.
useLayoutEffect is used because its cleanup runs synchronously as the boundary is hidden. A useEffect cleanup also runs on hide, but React schedules it a little later, so a sound could continue briefly. For a pause call, either works in practice. Prefer useLayoutEffect when the side effect is visible or audible.
Resuming after the boundary is visible again
The cleanup pauses the video, but nothing restarts it. When the user returns, the video stays paused at the same position. The element and its currentTime were preserved. This is usually what you want, because the user presses play when ready. Browsers also block autoplay with sound unless the user has interacted with the page, so resuming automatically from an Effect often fails.
Other DOM side effects to check
Look for anything that lives in the DOM or the browser and does not depend on React's render:
| Source | What keeps running while hidden | Cleanup idea |
|---|---|---|
| `<audio>`, `<video>` | Playback and sound | Call `pause()` in the cleanup |
| `<iframe>` embeds | The embedded page's scripts and media | Reset or remove `src`, or unmount the iframe while hidden |
| Listeners on `window` or `document` | Handlers still receive events | Remove them in the cleanup |
| Timers and subscriptions | Callbacks that update state | Clear or unsubscribe in the cleanup |
Listeners attached with React props, such as onClick on an element inside the boundary, are less of a worry. The element is hidden, so the user cannot interact with it. Listeners you attach manually to window, document, or a third-party object are your responsibility.
A way to find these bugs
Test every Activity boundary the same way:
- Start the activity inside it: play media, open a connection, start a timer.
- Hide the boundary.
- Check for sound, network traffic, console logs, or state updates.
If something continues, find the source and add a cleanup for it. Browser DevTools help. The Network tab shows traffic that should have stopped, and the Elements panel shows the hidden node still present.
Exercise
A tab panel contains an <audio> element with a ref. You wrapped the panel in <Activity mode={...}>, but music keeps playing after the user switches tabs. What do you add, and why is it needed?
Show answer
Add an Effect (preferably useLayoutEffect) that reads audioRef.current into a local variable and returns a cleanup that calls audio.pause(). Activity cleans up Effects when it hides, but it keeps the DOM node in the page, so the browser continues playing the audio unless your cleanup stops it.