React 19.2 Activity in Next.js 16: Hidden Routes, Re-running Effects, and Where useEffectEvent Fits — Field Notes
Headline: React's
<Activity>component, added in React 19.2, hides a subtree withdisplay: noneand cleans up its Effects while keeping its React state and DOM, and Next.js 16 withcacheComponents: trueuses it to keep up to 3 visited routes alive instead of unmounting them. Every Effect on a preserved page now runs its cleanup when the page is hidden and its setup again when the page comes back, which makesuseLayoutEffectcleanups and theuseEffectEventHook part of everyday Next.js code.
I enabled Cache Components in a Next.js 16 App Router project for its caching model and got a second behaviour change with it: pages stopped unmounting on navigation. Form drafts and filter panels survive a round trip, which is the point. Transient UI survives too — an open menu, a stale success banner, a video that keeps playing under display: none — and none of it throws an error. These notes cover how <Activity> behaves, what I reset and how, and where useEffectEvent fits. They are written against React 19.2 and later and Next.js 16.
Key takeaways
-
<Activity mode="hidden">keeps a subtree's React state and DOM but hides it withdisplay: noneand runs every Effect cleanup inside it, as if it had unmounted. - Next.js 16 with
cacheComponents: truehides routes in Activity instead of unmounting them and preserves up to 3 routes; the oldest is evicted and renders fresh. - DOM side effects survive hiding:
<video>,<audio>,<iframe>, page-level<style>tags and open menus need an explicit reset in auseLayoutEffector callback-ref cleanup. - Effects re-run on every hide-and-show cycle, so
useEffectEvent, stable since React 19.2, keeps non-reactive values out of dependency arrays without extra reconnects. - Hidden Activity content stays in the document, so end-to-end tests need visibility-aware queries: Playwright's
getByRoleskips hidden elements, a bare CSS locator does not.
What does React's <Activity> component actually do?
<Activity> is a React component, released in React 19.2 on October 1, 2025, that hides and restores part of the tree without unmounting it. Its only prop besides children is mode, either 'visible' (the default) or 'hidden'. A hidden boundary sets display: none on its children, runs the cleanup of every Effect inside it, and keeps re-rendering them at a lower priority when their props change. Switching back to 'visible' reveals the same DOM with the same state and runs each Effect's setup again.
'use client'; import { Activity, useState } from 'react'; import { Filters } from './filters'; import { Results } from './results'; export function SearchPage() { const [showFilters, setShowFilters] = useState(true); return ( <> <button onClick={() => setShowFilters((v) => !v)}>Filters</button> {/* Before: {showFilters && <Filters />} reset every checkbox on close */} <Activity mode={showFilters ? 'visible' : 'hidden'}> <Filters /> </Activity> <Results /> </> ); } The difference from conditional rendering is clearest side by side:
Conditional render ({open && <Panel />}) | <Activity mode="hidden"> | |
|---|---|---|
| React state and refs | Discarded | Kept |
DOM state (input values, scroll position, <details>, media time) | Discarded | Kept |
| Effects | Cleaned up | Cleaned up, re-created on show |
| DOM nodes | Removed from the document | Kept, hidden with display: none |
| Re-renders when props change | No | Yes, at lower priority |
One caveat from the React docs: a hidden Activity whose child returns only text renders nothing, because there is no DOM element to apply display: none to.
Why does my Next.js 16 page keep its state after I navigate away?
A Next.js 16 page keeps its state after navigation when cacheComponents: true is set, because Next.js then hides the previous route in an <Activity> boundary instead of unmounting it. Next.js preserves up to 3 routes this way; beyond that, the oldest route is evicted and renders fresh on its next visit. Without Cache Components, the App Router still unmounts pages on navigation.
// next.config.ts import type { NextConfig } from 'next'; const nextConfig: NextConfig = { cacheComponents: true, // also turns on Activity-based route preservation }; export default nextConfig; Before Cache Components, keeping a filter panel or a half-written draft across navigation meant hoisting state into a shared layout or an external store. Now preservation is the default, which turns every piece of page state into a decision: search filters and drafts should survive, while an open dropdown, a "Message sent!" banner or state that belonged to the previous signed-in user should not. Two resets I use at the page level:
- User changes: local state survives prop changes, including a new user ID. I key user-scoped forms with
key={userId}, and logout navigates withwindow.location.hreffor a full reload instead ofrouter.push(). - Pages that should start fresh on every visit: the Next.js 16.3 docs add
useRouter().bfcacheId. Used as thekeyof a Fragment, it resets the subtree on<Link>clicks,router.push()androuter.replace(), but still restores state on browser Back and Forward. The docs call it mainly a migration tool and recommend per-pattern resets for new code.
What breaks when a page is hidden instead of unmounted?
A hidden component behaves like an unmounted one for its Effects and like a mounted one for its DOM, so anything the DOM does on its own keeps happening. These are the cases I check on every page that can be preserved:
- Media:
<video>,<audio>and<iframe>elements keep playing underdisplay: none; unmounting used to stop them for free. - Transient open state: a dropdown or popover that was open when the user left is still open when they come back.
- Page-level styles: a
<style>tag that sets CSS variables or z-index on:rootkeeps applying to whichever page is visible. - Mount-only logic: an Effect that focuses an input when
isDialogOpenbecomestruedoes not fire again ifisDialogOpenwas preserved astrue. The Next.js guide fixes this by deriving dialog state from a search param. - Duplicate IDs: a hard-coded
idin a component rendered on two preserved routes now exists twice in one document, and bothdocument.getElementById()and<label htmlFor>resolve to the first match in tree order, which can be the hidden copy.useId()avoids the collision.
The fix for media, open state and styles is the same: reset them in a cleanup function, which now runs on hide as well as on unmount. The React and Next.js docs both use useLayoutEffect for this, because its cleanup runs synchronously as the UI is hidden, while a regular Effect's cleanup can be delayed by a re-suspending Suspense boundary or a View Transition.
'use client'; import { useLayoutEffect, useRef, useState } from 'react'; import { SpeedMenu } from './speed-menu'; export function LessonPlayer({ src }: { src: string }) { const videoRef = useRef<HTMLVideoElement>(null); const [menuOpen, setMenuOpen] = useState(false); useLayoutEffect(() => { const video = videoRef.current; return () => { video?.pause(); // hidden DOM keeps playing otherwise; currentTime is kept setMenuOpen(false); // transient UI should not survive navigation }; }, []); return ( <> <video ref={videoRef} src={src} controls playsInline /> <button onClick={() => setMenuOpen((o) => !o)}>Speed</button> {menuOpen && <SpeedMenu />} </> ); } Callback refs follow the same lifecycle. Since React 19 a ref callback can return a cleanup function, and Activity runs that cleanup on hide; the Next.js guide uses it to switch a page's <style> tag off with style.media = 'not all' and back on with style.media = ''.
Where does useEffectEvent fit when Effects re-run on every show?
useEffectEvent is a React Hook, stable since React 19.2, that wraps logic fired from an Effect so it always reads the latest props and state without becoming an Effect dependency. It matters more under Activity because every hide-and-show cycle tears down and re-creates each subscription, and an Effect that lists UI preferences as dependencies also reconnects every time one of those preferences changes.
My clearest case is a live feed: one WebSocket per store, plus a sound preference and a status filter that decide whether a new order plays a chime. Only storeId should reconnect the socket:
'use client'; import { useEffect, useEffectEvent, useState } from 'react'; import { OrderList, type Order } from './order-list'; export function LiveOrders({ storeId, soundOn }: { storeId: string; soundOn: boolean }) { const [orders, setOrders] = useState<Order[]>([]); const [filter, setFilter] = useState<Order['status'] | 'all'>('all'); // Always sees the latest soundOn and filter, never re-runs the Effect const onOrder = useEffectEvent((order: Order) => { setOrders((prev) => [order, ...prev]); if (soundOn && (filter === 'all' || order.status === filter)) { void new Audio('/chime.mp3').play(); } }); useEffect(() => { const socket = new WebSocket(`wss://api.example.com/stores/${storeId}/orders`); socket.onmessage = (event) => onOrder(JSON.parse(event.data)); return () => socket.close(); // runs on unmount and when Activity hides the page }, [storeId]); // onOrder is deliberately not a dependency return <OrderList orders={orders} filter={filter} onFilterChange={setFilter} />; } While the page is hidden, the socket is closed, so a preserved route holds no live connection; when the page becomes visible, the Effect reconnects once with the current storeId. The rules, which eslint-plugin-react-hooks v6 and later enforce:
- Call an Effect Event only inside
useEffect,useLayoutEffect,useInsertionEffector another Effect Event in the same component, never during render. - Do not pass an Effect Event to child components or other Hooks, and do not list it in a dependency array.
- An Effect Event's identity changes on every render on purpose, so an Effect that depends on it re-runs every render and makes the mistake visible.
- Do not use
useEffectEventto drop a real dependency: if a newpageUrlshould log a new page view,pageUrlstays in the dependency array.
Effects that run on every hide-to-visible transition also break "first mount only" logic, such as a one-time impression event. Refs are not reset when Activity hides a subtree, so a useRef(false) flag flipped inside the Effect tells the first mount apart from a re-show.
Can <Activity> load a tab before the user opens it?
Yes: a boundary that starts in mode="hidden" still renders its children at low priority without mounting their Effects, so code, data, CSS and images can load before the content is shown. Only data read through Suspense, such as a promise unwrapped with use(), is fetched during that pre-render; a fetch() inside useEffect waits until the boundary becomes visible.
'use client'; import { Activity, Suspense, use, useState } from 'react'; type Review = { id: string; text: string }; export function Reviews({ reviewsPromise }: { reviewsPromise: Promise<Review[]> }) { const [open, setOpen] = useState(false); return ( <> <button onClick={() => setOpen((o) => !o)}>Reviews</button> <Activity mode={open ? 'visible' : 'hidden'}> <Suspense fallback={<p>Loading reviews...</p>}> <ReviewList reviewsPromise={reviewsPromise} /> </Suspense> </Activity> </> ); } function ReviewList({ reviewsPromise }: { reviewsPromise: Promise<Review[]> }) { const reviews = use(reviewsPromise); // resolves during the hidden pre-render return <ul>{reviews.map((r) => <li key={r.id}>{r.text}</li>)}</ul>; } The parent Server Component starts the query and passes the unresolved promise down, so the request begins on the server and can finish while the reviews are still hidden. Activity boundaries also take part in Selective Hydration the way Suspense boundaries do, so React can make the rest of the page interactive before it hydrates a heavy subtree, even one that is always visible. I still do not wrap every tab in Activity: hidden subtrees keep their DOM in memory and re-render when their props change, so I reserve hidden pre-rendering for content the user is likely to open next.
How do I stop Playwright from matching hidden Activity content?
Use visibility-aware queries, because hidden Activity content stays in the document with display: none and plain CSS selectors still match it. In Playwright, getByRole, getByLabel and getByPlaceholder skip hidden elements, while page.locator('.product-card').first() can return a card from a preserved route the user has already left.
// Role-based queries skip hidden elements await page.getByRole('button', { name: 'Save' }).click(); // CSS locators need an explicit visibility filter under Activity await page.locator('.product-card').filter({ visible: true }).first().click(); For Effects without proper cleanup, <StrictMode> is the cheapest check: the React docs note that Strict Mode eagerly performs Activity unmounts and mounts in development, which surfaces Effects that set something up and never tear it down.
FAQ
Q: Is <Activity mode="hidden"> the same as hiding a component with CSS?
A: No. CSS display: none alone leaves Effects running, so timers, subscriptions and sockets stay active. A hidden <Activity> boundary also runs every Effect cleanup and lowers the render priority of the subtree, while keeping its state and DOM.
Q: Does Next.js 16 keep every visited page alive?
A: No. Activity-based route preservation applies only when cacheComponents: true is enabled, and Next.js keeps at most 3 routes; the oldest is evicted and renders fresh on its next visit.
Q: Should useEffectEvent replace the "latest value in a ref" pattern?
A: For callbacks fired from your own Effects, yes: useEffectEvent does the same job and the React Hooks linter understands it. Keep a ref only when the callback has to be passed to another component or Hook, which Effect Events do not allow.
Q: Do components inside a hidden Activity still re-render?
A: Yes. When a hidden boundary's props change, React re-renders its children at a lower priority than visible content, but their Effects stay unmounted until the boundary becomes visible again.
Q: Can screen readers reach hidden Activity content?
A: No. display: none removes hidden Activity content from the accessibility tree. Hard-coded id values can still collide with the visible page, so labels and ARIA references should use IDs from useId().
Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.