Sub topic 3
Pitfalls and Trade-offs with React Activity
Assume you know React function components, useState, useEffect, and component mounting and unmounting. Activity is available in React 19.2 and later.
Pitfalls: Media Playback and DOM Side Effects
When an Activity becomes hidden, React preserves its state and DOM, but cleans up its Effects. A video element therefore remains in the DOM, while an Effect that controls the video should stop playback:
import { useEffect, useRef } from 'react';
function VideoPanel() {
const videoRef = useRef(null);
useEffect(() => {
const video = videoRef.current;
return () => {
video.pause();
};
}, []);
return <video ref={videoRef} controls src="/clip.mp4" />;
}The same pattern applies to timers, subscriptions, event listeners, observers, and external connections. Do not assume that hiding a DOM node automatically stops its behavior. CSS hiding has no Effect cleanup.
Pre-rendering and Update Priority
A hidden Activity can render content before the user opens it. This can make a settings screen or tab feel faster on first display. React schedules updates to hidden trees at a lower priority, so visible interactions get preference.
Lower priority does not mean no work. A hidden component can still consume time when it renders, especially if its props change or its parent renders frequently.
Cost of Keeping Hidden Trees Alive
Activity uses memory for the preserved component state and DOM. Large tables, editors, maps, and many hidden tabs can increase memory use. Hidden content can also retain references to data and can still receive lower-priority rendering work.
Use Activity for UI that users revisit and where preserving input or scroll position matters. Avoid keeping every rarely used screen alive.
Activity or Something Else?
- Use conditional rendering when discarded state is acceptable.
- Use Activity when a screen should reopen exactly as the user left it.
- Use CSS hiding only when Effects should continue running.
- Lift state up when only a small, serializable value needs to survive unmounting.
Exercise
A hidden video keeps playing. What should you check first?
Show answer
Check that the component's Effect cleanup calls video.pause() when the Activity becomes hidden.