Capítulo 66 de 116

Chapter 66: Activity

Core Idea

<Activity> lets a subtree be visually hidden and de-prioritized while keeping its component state alive — the built-in primitive for "keep this screen/tab mounted in the background" UX (tab switching, pre-rendering the next likely screen) without losing scroll position, form input, or other local state.

Key Concepts

  • Two modes: <Activity mode="visible"> (default, renders and displays normally) and <Activity mode="hidden"> (keeps the subtree mounted with its state intact, but visually hidden and deprioritized for rendering work).
  • State preservation across visibility toggles: switching a component between visible/hidden Activity modes preserves its internal state, unlike unmounting it (Ch 30) — this is the mechanism behind, e.g., switching between app tabs without losing each tab's scroll position or in-progress form state.
  • Deprioritized rendering: updates inside a hidden Activity subtree are processed at lower priority than visible UI — useful for pre-rendering a likely-next screen in the background without competing with the currently visible UI's responsiveness.
  • Effects don't run while hidden in the way they do for a visible/mounted tree — the docs treat a hidden Activity subtree similarly to being "paused," not identical to a fully active mount, which matters for any Effect-driven subscriptions/connections inside it.

Code Examples

<Activity mode={activeTab === 'posts' ? 'visible' : 'hidden'}>
  <PostsTab />
</Activity>
  • What it demonstrates: PostsTab's state (scroll position, any local useState) survives switching away to a different tab and back, because it stays mounted under Activity rather than being unmounted.

Key Takeaways

  1. Reach for Activity when you need "hide but keep state" semantics — plain conditional rendering (Ch 16) unmounts and loses state entirely.
  2. Hidden-mode content still exists in the tree and can be pre-rendered at low priority, which is a legitimate technique for perceived-instant tab/screen switches.
  3. Effects inside a hidden subtree behave differently from a normal visible mount — don't assume Effect-driven subscriptions continue exactly as before while hidden.

Connects To

  • Ch 30 (Preserving and Resetting State): the unmount-loses-state behavior this component is an alternative to.
  • Ch 70 (Suspense): the related primitive for coordinating loading states, often used alongside Activity.