--- title: How Next.js preserves UI state with Activity nav_title: Preserving UI state description: Learn how React's Activity component preserves UI state across navigations in Next.js and how to control what resets. related: title: Related description: Learn more about Cache Components and preserving UI state. links: - app/getting-started/caching - app/guides/migrating-to-cache-components --- > **Good to know:** This guide assumes [Cache Components](/docs/app/getting-started/caching) is enabled. Enable it by setting [`cacheComponents: true`](/docs/app/api-reference/config/next-config-js/cacheComponents) in your Next config file. Before Cache Components, preserving page-level state across navigations required workarounds like hoisting state to a [shared layout](/docs/app/getting-started/layouts-and-pages#nesting-layouts) or using an external store. With Cache Components, Next.js preserves state and DOM out of the box. Instead of unmounting pages on navigation, Next.js hides them using React's [``](https://react.dev/reference/react/Activity) component. Activity keeps the DOM in the document (hidden with `display: none`), so both React state and DOM state are preserved: form drafts, scroll positions, expanded `
` elements, video playback progress, and more. Next.js preserves up to 3 routes. Beyond that, the oldest route is evicted and will re-render fresh. > **Good to know:** Opt-out strategies are being considered for gradual migration. ## Choosing what to preserve Activity preserves all component state and DOM state by default. For each piece of state, you decide whether that's the right behavior for your UI. The patterns below show common scenarios and how to handle both sides. ### Expandable UI (dropdowns, accordions, panels) When a user navigates away and returns, Activity preserves the open/closed state of expandable elements. **When to keep it:** A sidebar with expanded sections, a FAQ accordion, or a filters panel. The user set up their view intentionally, and restoring it avoids re-doing that work. **When to reset it:** A dropdown menu or popover triggered by a button click. These are transient interactions, not persistent view state. Returning to a page with a dropdown already open is not user friendly. To reset transient open/closed state, close it in a `useLayoutEffect` cleanup function: ```tsx highlight={8-13} 'use client' import { useState, useLayoutEffect } from 'react' function SettingsDropdown() { const [isOpen, setIsOpen] = useState(false) // Close dropdown when this component becomes hidden useLayoutEffect(() => { return () => { setIsOpen(false) } }, []) return (
{isOpen && (
)}
) } ``` When Activity hides this component, the cleanup function runs and resets `isOpen`. When the page becomes visible again, the dropdown is closed. Using `useLayoutEffect` ensures the cleanup runs synchronously before the component is hidden, avoiding any flash of stale state. You can also use `Link`'s [`onNavigate`](/docs/app/api-reference/components/link#onnavigate) callback to close dropdowns immediately when a navigation link is clicked. ### Dialog and initialization logic Activity preserves dialog open/closed state. This also affects Effects that run based on that state. **When to keep it:** A multi-step wizard or a settings panel that the user was actively working in. Preserving the step and input state avoids losing progress. **When to reset it:** A dialog that runs initialization logic (like focusing an input) each time it opens. If the user navigated away while the dialog was open, Activity preserves `isDialogOpen: true`. Opening it again sets it to `true` when it's already `true`, so no state change happens and the Effect doesn't re-run. Consider this example: ```tsx 'use client' import { useState, useRef, useEffect } from 'react' function ProductTab() { const [isDialogOpen, setIsDialogOpen] = useState(false) const inputRef = useRef(null) useEffect(() => { if (isDialogOpen) { inputRef.current?.focus() } }, [isDialogOpen]) // ... } ``` If the user navigated away while the dialog was open, returning and opening the dialog won't trigger the focus Effect because `isDialogOpen` was already `true`. To fix this, derive the dialog state from something outside the preserved component state like a search param: ```tsx highlight={3,7-9,20,25} 'use client' import { useSearchParams, useRouter } from 'next/navigation' import { useEffect, useRef } from 'react' function ProductTab() { const searchParams = useSearchParams() const router = useRouter() const isDialogOpen = searchParams.get('edit') === 'true' const inputRef = useRef(null) useEffect(() => { if (isDialogOpen) { inputRef.current?.focus() } }, [isDialogOpen]) return (
{isDialogOpen && ( )}
) } ``` With this approach, `isDialogOpen` derives from the URL rather than component state. When navigating away and returning, the search param is cleared (the URL changed), so `isDialogOpen` becomes `false`. Opening the dialog sets the param, which changes `isDialogOpen` and triggers the Effect. ### Forms, inputs, and state Activity preserves form input values (text fields, selected options, checkbox states), submission results, and status messages across navigations. **When to keep it:** A search page with filters, a draft the user was composing, or a settings form with unsaved changes. Preserving input state is one of the biggest UX wins because the user doesn't lose work. **When to reset it:** A "new transaction" flow where each visit should start fresh, or a form where stale success/error messages would be confusing in a new context. #### Resetting form state on submit Consider a page where the user creates a new item. After submitting, `router.push` navigates to the new record. Since Activity preserves the page, navigating back shows the previous name still in the form. Reset state in the event handler to keep the form fresh: ```tsx filename="app/new/page.tsx" highlight={13} 'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' export default function NewItemPage() { const [name, setName] = useState('') const router = useRouter() async function handleSubmit(e: React.FormEvent) { e.preventDefault() const item = await createItem({ name }) setName('') router.push(`/items/${item.id}`) } return (
setName(e.target.value)} />
) } ``` #### Resetting stale status messages If after submitting you set a status into state to render a feedback message, there's often not a reliable user-initiated event to clear it. The user might navigate via `next/link` elements out of your control, or via browser controls. Navigating back to the form shows a stale message. In this case, you may use a `useLayoutEffect` cleanup to reset the form and state: ```tsx highlight={17-26} 'use client' import { useState, useRef, useLayoutEffect } from 'react' function ContactForm() { const [name, setName] = useState('') const [status, setStatus] = useState<'idle' | 'success'>('idle') const shouldReset = useRef(false) async function handleSubmit(e: React.FormEvent) { e.preventDefault() await sendMessage({ name }) setStatus('success') shouldReset.current = true } // Reset stale success message when Activity hides this component useLayoutEffect(() => { return () => { if (shouldReset.current) { shouldReset.current = false setStatus('idle') setName('') } } }, []) return (
setName(e.target.value)} /> {status === 'success' &&

Message sent!

}
) } ``` The `shouldReset` ref ensures the cleanup only runs after a successful submission. If the user navigates away mid-draft without submitting, their input is preserved. If you use [`useActionState`](https://react.dev/reference/react/useActionState), the same approach applies. See [Reset state](https://react.dev/reference/react/useActionState#reset-state) in the React docs for how to add a `RESET` action to your reducer.
Resetting all form fields with a callback ref You can use a callback ref to call `form.reset()` when Activity hides the component: ```tsx
{ return () => form?.reset() }} >
``` This resets all fields whenever the user navigates away.
## State and authentication Activity preserves local component state (`useState`, DOM input values) across navigations, including authentication changes. This is standard React behavior: props changing (such as receiving a new user) triggers a re-render but does not reset existing state. A draft composed by one user shouldn't be visible to another. For logout flows, using `window.location.href` instead of `router.push` triggers a full page reload, clearing all client-side state. To reset specific state when the user changes without a full reload: ```tsx 'use client' import { useState, useEffect, useRef } from 'react' function UserScopedForm({ userId }: { userId: string | null }) { const [draft, setDraft] = useState('') const lastUserIdRef = useRef(null) useEffect(() => { if (lastUserIdRef.current !== null && lastUserIdRef.current !== userId) { setDraft('') // Reset on user change } lastUserIdRef.current = userId }, [userId]) return