React 19.2 - You should try <Activity />
The TLDR is <Activity> is a new React component that lets you hide and restore UI and state without unmounting components.
Here’s a snippet of how to show UI components:
<Activity mode="visible">
<Sidebar />
</Activity>
Here’s a snippet of how to hide UI components:
<Activity mode="hidden">
<SlowTab />
</Activity>
On the css level, it sets display to be none with prop mode is hidden. All states are preserved while side effects are paused.
Why hiding without unmounting matters?
- States are preserved on hiding
- Pre-rendering
This is allows developers to build UX that is more fluid, instant and alive to the end user. Imaging you have to load a list of data from async request for multiple tabs, with <Activity>, you can load the data once user clicks on the tab and if user decides to come back, all states are preserved. If there’s a Chart with expensive data initialization and complex DOM, it would be pre-rendered and be ready for side effects. Technically, the virtual DOM nodes are created, useState, useReducer hooks are resolved.
What state is preserved?
When props mode is hidden, useState, useRef, useReducer, useMemo, useCallback and DOM states are preserved. This means, form inputs, counters, toggles, DOM references, scroll positions, etc are preserved. However, side effects like from useEffect and useLayoutEffect are cleaned up and they will be re-run when the mode is visible.
When would we use it?
The most useful cases I believe is probably:
- Hiding UI without resetting state (ie. sidebar, tabs)
- Pre-rendering - no jank, no filter