---
title: How Next.js preserves UI state with Activity
description: "Learn how React's Activity component preserves UI state across navigations in Next.js and how to control what resets."
url: "https://nextjs.org/docs/app/guides/preserving-ui-state"
docs_index: /docs/llms.txt
lastUpdated: 2026-12-01
navTitle: "Preserving UI state"
prerequisites:
  - "Guides: /docs/app/guides"
related:
  - /docs/app/getting-started/caching
  - /docs/app/guides/migrating-to-cache-components
---

> For an index of all documentation, see [/docs/llms.txt](/docs/llms.txt).

> **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 [`<Activity>`](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 `<details>` 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:**
>
> Use [`useRouter().bfcacheId`](/docs/app/api-reference/functions/use-router#bfcacheid) as a [React `key`](https://react.dev/learn/preserving-and-resetting-state#option-2-resetting-state-with-a-key): a single `<Fragment key={bfcacheId}>` resets an entire subtree on push or replace navigations (including `<Link>` clicks and `router.push` / `router.replace`) while still restoring state on browser back/forward. `bfcacheId` is mainly a migration tool. For new code, prefer the per-pattern resets below.

## Choosing what to preserve

Activity preserves all component state and DOM state by default. Whether to preserve or reset a piece of state depends on how people use the UI. The examples below illustrate patterns you can apply to other components with the same state or cleanup needs.

### 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.

When React state should reset on hide, update it in a `useLayoutEffect` cleanup. For example, this dropdown closes when Activity hides the component:

```tsx highlight={8-10}
'use client'

import { useLayoutEffect, useState } from 'react'

function SettingsDropdown() {
  const [isOpen, setIsOpen] = useState(false)

  useLayoutEffect(() => {
    return () => setIsOpen(false)
  }, [])

  return (
    <div>
      <button onClick={() => setIsOpen((open) => !open)}>Options</button>
      {isOpen && (
        <ul>
          <li>
            <button>Edit Profile</button>
          </li>
          <li>
            <button>Change Password</button>
          </li>
        </ul>
      )}
    </div>
  )
}
```

The cleanup resets `isOpen` before Activity hides the component, so the dropdown is closed when the user returns.

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.

#### Native popovers

Native popovers keep their open state in the DOM. In this example, a `useLayoutEffect` cleanup calls [`hidePopover()`](https://developer.mozilla.org/docs/Web/API/HTMLElement/hidePopover) to close the popover when Activity hides the component.

```tsx highlight={9-12}
'use client'

import { useId, useLayoutEffect, useRef } from 'react'

function SettingsPopover() {
  const popoverId = useId()
  const popoverRef = useRef<HTMLDivElement>(null)

  useLayoutEffect(() => {
    const popover = popoverRef.current
    return () => popover?.hidePopover()
  }, [])

  return (
    <>
      <button popoverTarget={popoverId}>Options</button>
      <div id={popoverId} ref={popoverRef} popover="auto">
        <button>Edit Profile</button>
        <button>Change Password</button>
      </div>
    </>
  )
}
```

Because hidden pages remain in the DOM, reusing a hard-coded ID across pages can associate a button with the wrong popover. [`useId`](https://react.dev/reference/react/useId) gives each component instance a unique ID, keeping the button associated with its own popover. The same applies to IDs used by labels, `aria-describedby`, and the `form` attribute. For radio groups without separate forms, give each instance its own group name.

### Dialog and initialization logic

Activity preserves a dialog's open/closed state. When Activity shows the component again, React re-runs its Effects, including initialization logic such as focusing an input.

**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 temporary edit dialog that should be closed when the user returns.

To reset the open/closed state on hide, use a `useLayoutEffect` cleanup as in the [dropdown example](#expandable-ui-dropdowns-accordions-panels).

For controlled dialogs rendered through a portal, reset the open state in the component that owns it, as in the dropdown example.

For native dialogs opened with `showModal()`, use a ref to the `<dialog>` element and call [`close()`](https://developer.mozilla.org/docs/Web/API/HTMLDialogElement/close) during cleanup. This closes the dialog when Activity hides the component.

```tsx highlight={3}
useLayoutEffect(() => {
  const dialog = dialogRef.current
  return () => dialog?.close()
}, [])
```

#### Controlling a dialog with the URL

If a dialog should open when visiting a particular URL, derive its state from a search parameter. For example, this dialog opens when the URL includes `?edit=true`:

```tsx highlight={11,20-22,26-29,31,36}
'use client'

import { useSearchParams, useRouter } from 'next/navigation'
import { Suspense, useEffect, useRef } from 'react'

function ProductTab() {
  const router = useRouter()

  return (
    <>
      <button onClick={() => router.push('?edit=true')}>Edit Product</button>
      <Suspense fallback={null}>
        <ProductDialog />
      </Suspense>
    </>
  )
}

function ProductDialog() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const isDialogOpen = searchParams.get('edit') === 'true'
  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (isDialogOpen) {
      inputRef.current?.focus()
    }
  }, [isDialogOpen])

  if (!isDialogOpen) return null

  return (
    <dialog open>
      <input ref={inputRef} placeholder="Product name" />
      <button onClick={() => router.replace('?', { scroll: false })}>
        Close
      </button>
    </dialog>
  )
}
```

Keeping the button outside the [`Suspense` boundary](/docs/app/api-reference/functions/use-search-params#prerendering) lets it prerender while the dialog reads search parameters. The [empty fallback](/docs/app/guides/streaming#choosing-a-fallback) avoids showing editor loading UI on URLs that don't open the dialog. If a parent already provides a suitable boundary, omit the boundary in this example.

Returning through a link without `?edit=true` closes the dialog. Browser back and forward navigation restore the URL for that history entry, so returning to a URL with `?edit=true` opens it again.

### 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 highlight={13} title="app/new/page.tsx"
'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.SubmitEvent<HTMLFormElement>) {
    e.preventDefault()
    const item = await createItem({ name })
    setName('')
    router.push(`/items/${item.id}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button type="submit">Create</button>
    </form>
  )
}
```

#### 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.SubmitEvent<HTMLFormElement>) {
    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 (
    <form onSubmit={handleSubmit}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      <button type="submit">Send</button>
      {status === 'success' && <p>Message sent!</p>}
    </form>
  )
}
```

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. For more on building responsive interactions with these hooks, see the [Building interactive apps](/docs/app/guides/interactive-apps) guide.

**Resetting uncontrolled form fields with a callback ref**

For uncontrolled inputs, a callback ref can call [`form.reset()`](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/reset) when Activity hides the component. This restores the inputs to their default values:

```tsx highlight={3-5}
'use client'

function resetOnHide(form: HTMLFormElement | null) {
  return () => form?.reset()
}

function ContactForm() {
  return (
    <form ref={resetOnHide}>
      <input name="email" />
      <input name="message" />
      <button type="submit">Send</button>
    </form>
  )
}
```

React runs the previous [ref callback’s cleanup](https://react.dev/reference/react-dom/components/common#ref-callback) when the callback changes. Defining `resetOnHide` outside the component keeps it stable, so a re-render does not unexpectedly reset the form.

`form.reset()` does not reset React state. For controlled inputs, reset the state passed to `value` or `checked`, as in the examples above.

### State updated while hidden

State can change while Activity keeps a page hidden. In development, Strict Mode can run Effect cleanup again when a hidden page becomes visible. An unconditional reset in that cleanup can discard updates received while hidden. See [Tracking whether an Effect has run before](#tracking-whether-an-effect-has-run-before) for more on the Effect lifecycle.

For example, an inbox uses Effect cleanup to clear its notification when the user leaves. A new notification arrives while the inbox is hidden. If cleanup runs again on return, it clears the new notification before the user sees it.

Clear the previous notification from the navigation handler instead:

```tsx highlight={11} title="app/inbox/navigation.tsx"
'use client'

import Link from 'next/link'

export function InboxNavigation({
  clearNotification,
}: {
  clearNotification: () => void
}) {
  return (
    <Link href="/settings" onNavigate={clearNotification}>
      Settings
    </Link>
  )
}
```

This clears the notification when navigating through this link. To cover browser controls and other links, [observe route changes from a shared layout](/docs/app/api-reference/functions/use-pathname#do-something-in-response-to-a-route-change) and clear the notification for the page being left.

## 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 a form when the user changes without a full reload, key it by user ID. React creates a new form for each identity, including when signing in or out.

```tsx
'use client'

import { useState } from 'react'

function UserScopedForm({ userId }: { userId: string | null }) {
  return <DraftForm key={userId} />
}

function DraftForm() {
  const [draft, setDraft] = useState('')

  return <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />
}
```

## Global styles

Page-level styles (CSS variables, z-index, global classes) can affect visible pages when the originating component is hidden by Activity. You likely want to disable them when hidden: a hidden page's accent color or z-index overrides shouldn't leak into the visible page.

Use a callback ref to toggle the stylesheet's `media` attribute:

```tsx
<style
  ref={(style) => {
    if (style) style.media = '' // Enable when visible
    return () => {
      if (style) style.media = 'not all' // Disable when hidden
    }
  }}
>
  {`:root { --page-accent: blue; }`}
</style>
```

Or use `useLayoutEffect` when managing multiple style elements or more complex cleanup:

```tsx
'use client'

import { useLayoutEffect, useRef } from 'react'

function PageWithStyles() {
  const styleRef = useRef<HTMLStyleElement>(null)

  useLayoutEffect(() => {
    if (styleRef.current) styleRef.current.media = ''
    return () => {
      if (styleRef.current) styleRef.current.media = 'not all'
    }
  }, [])

  return <style ref={styleRef}>{`:root { --page-accent: blue; }`}</style>
}
```

When Activity hides the component, the cleanup sets `media="not all"`, which disables the stylesheet. When visible again, the Effect re-runs and resets `media` to enable it.

### The `:has` selector

A [`:root:has(...)`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:has) rule applies styles based on its selector. Neither the selected element nor the matched element knows about the relationship. It's valid CSS, but it bypasses React's data flow and couples unrelated components.

For global state, prefer a `data-*` attribute that React owns:

```tsx
<html data-modal-open={modalOpen ? "true" : undefined}>
```

```css
html[data-modal-open='true'] {
  overflow: hidden;
}
```

Reserve `:has()` for local parent/child styling within a component:

```css
.card:has(img) {
  padding-top: 0;
}
```

This isn't only a React data-flow or Next.js concern. Broad `:has()` selectors are a real performance bottleneck. See [Performance considerations](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:has#performance_considerations) on MDN.

> **Good to know:**
>
> If the hidden component itself defines the global `:has` rule, the toggle from the section above disables it along with the component's other styles.

## Testing

Hidden Activity content has `display: none` but remains in the document. This applies both to routes preserved by Cache Components and to content you hide with `<Activity>` directly. It affects end-to-end testing with tools like Playwright, Cypress, or Puppeteer:

- **DOM queries can find hidden elements.** Selectors may match elements regardless of visibility.
- **Interactions with hidden elements fail or time out.** Most tools wait for an element to become visible before interacting, but waiting doesn't narrow a query that matches both a visible and a hidden element. Playwright reports this as a strict mode violation.
- **Assertions may match hidden content.** Be explicit about visibility when asserting element presence.

### Use visibility-aware selectors

Prefer locators that query the accessibility tree, which leaves out hidden elements, or filter matches by visibility before acting on them. In Playwright, `getByRole` queries exclude hidden elements by default:

```ts
// Good - getByRole excludes hidden elements by default
await page.getByRole('button', { name: 'Submit' }).click()
await page.getByRole('textbox', { name: 'Email' }).fill('test@example.com')
```

Other locators, including `getByLabel`, `getByPlaceholder`, and `.locator()`, can match hidden elements. Filter them by visibility explicitly:

```ts
// Filter by visibility explicitly
await page
  .getByLabel('Email')
  .filter({ visible: true })
  .fill('test@example.com')
await page.getByPlaceholder('Search...').filter({ visible: true }).fill('query')
await page.locator('.product-card').filter({ visible: true }).first().click()
await page
  .locator('[data-testid="timer"]')
  .filter({ visible: true })
  .textContent()

// Avoid - may match hidden elements in Activity boundaries
await page.getByLabel('Email').fill('test@example.com')
await page.locator('.product-card').first().click()
```

`getByRole` is robust to Activity, tabbed navigation, accordions, and any other pattern that keeps hidden content in the DOM. It queries the accessibility tree, which excludes hidden elements. Which locators match hidden elements varies between testing tools and their versions, so check your tool's documentation for its locators and test helpers to confirm.

## Using Activity in your components

Cache Components uses Activity automatically at the route level, but you can also use `<Activity>` directly in your own components. This is useful for tabs, expandable panels, or any UI where you want to hide content without unmounting it.

### Prerendering hidden content

Activity can prerender content the user hasn't seen yet. Hidden boundaries render at lower priority. Combined with Suspense, this lets you prefetch data for content the user is likely to view next.

A Server Component can start fetching data immediately and pass the promise to a client component. The client component uses Activity to hide the content until the user requests it, and `use()` to resolve the promise when rendering:

```tsx title="app/page.tsx"
import { Suspense } from 'react'
import { ExpandableComments } from './expandable-comments'

async function getCommentsData() {
  return db.comments.findMany()
}

export default function Page() {
  const commentsPromise = getCommentsData()

  return (
    <article>
      <h1>Post Title</h1>
      <p>Main content visible immediately...</p>

      <ExpandableComments commentsPromise={commentsPromise} />
    </article>
  )
}
```

```tsx title="app/expandable-comments.tsx"
'use client'

import { Activity, Suspense, useState, use } from 'react'

type Comment = { id: string; text: string; author: string }

export function ExpandableComments({
  commentsPromise,
}: {
  commentsPromise: Promise<Comment[]>
}) {
  const [expanded, setExpanded] = useState(false)

  return (
    <>
      <button onClick={() => setExpanded((e) => !e)}>
        {expanded ? 'Hide Comments' : 'Show Comments'}
      </button>

      <Activity mode={expanded ? 'visible' : 'hidden'}>
        <Suspense fallback={<CommentsSkeleton />}>
          <Comments commentsPromise={commentsPromise} />
        </Suspense>
      </Activity>
    </>
  )
}

function Comments({
  commentsPromise,
}: {
  commentsPromise: Promise<Comment[]>
}) {
  const comments = use(commentsPromise)
  return (
    <ul>
      {comments.map((c) => (
        <li key={c.id}>{c.text}</li>
      ))}
    </ul>
  )
}

function CommentsSkeleton() {
  return <div>Loading comments...</div>
}
```

The Server Component starts fetching comments immediately and passes the promise to `ExpandableComments`. Activity renders the hidden content at lower priority. When the user clicks "Show Comments", the comments appear immediately if the data is ready. Otherwise, Suspense shows `CommentsSkeleton` until the request completes.

### Effect and media cleanup

When Activity hides content, React runs Effect cleanup functions as it does on unmount. This means timers, subscriptions, and media playback pause automatically if you have proper cleanup:

```tsx
'use client'

import { useEffect, useState } from 'react'

function LiveTimer() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    const id = setInterval(() => setCount((c) => c + 1), 1000)
    return () => clearInterval(id) // Pauses when hidden
  }, [])

  return <p>Count: {count}</p>
}
```

For media elements like `<video>` and `<audio>`, `display: none` does not stop playback. Add explicit cleanup with `useLayoutEffect`:

```tsx
'use client'

import { useLayoutEffect, useRef } from 'react'

function VideoPlayer({ src }: { src: string }) {
  const videoRef = useRef<HTMLVideoElement>(null)

  useLayoutEffect(() => {
    const video = videoRef.current
    return () => {
      video?.pause() // Pauses when hidden, preserves playback position
    }
  }, [])

  return <video ref={videoRef} src={src} controls />
}
```

When the component becomes visible again, Effects re-run and playback position is preserved since the DOM node was never removed.

If cleanup removes or changes a DOM property, restore it in the Effect's setup. For example, the following Effect releases the video's media resource while hidden and restores its source when shown. It replaces the Effect in `VideoPlayer` above.

```tsx highlight={4,7-8}
useLayoutEffect(() => {
  const video = videoRef.current
  if (!video) return
  video.src = src
  return () => {
    video.pause()
    video.removeAttribute('src')
    video.load()
  }
}, [src])
```

Releasing the source also resets playback position. If you only need to stop playback, use the earlier `pause()` example to preserve it.

### Tracking whether an Effect has run before

Effects run on every hide-to-visible transition, not just the initial mount. A ref can record whether an Effect has run before:

```tsx
'use client'

import { useEffect, useRef } from 'react'

function TrackedComponent() {
  const hasRunRef = useRef(false)

  useEffect(() => {
    if (!hasRunRef.current) {
      hasRunRef.current = true
      console.log('Effect ran for the first time')
    } else {
      console.log('Effect ran again')
    }
  }, [])

  return <div>...</div>
}
```

The ref persists across hide/show cycles. In development, [Strict Mode runs an extra setup and cleanup cycle](https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-re-running-effects-in-development), so the `else` branch can also run on initial mount. This records whether the Effect has run before, not whether navigation occurred. Make setup and cleanup safe to repeat.

## Examples

The [Activity Patterns Demo](https://react-activity-patterns.labs.vercel.dev) ([source](https://github.com/nextjs/react-activity-patterns)) is a Next.js app with Cache Components enabled and three routes. Navigate between them to see state preservation in action:

- **Data** — sortable table and selectable list that keep their state across navigations, plus a reviews section that prerenders in the background
- **Forms** — filter panel with DOM state (`<details>`, checkboxes, text inputs) that persists, and a newsletter form that resets after submission using `useLayoutEffect` cleanup
- **Side Effects** — a live timer that pauses when you navigate away and resumes when you return, and a video player that auto-pauses with playback position preserved

## Related

Learn more about Cache Components and preserving UI state.

- [Caching](/docs/app/getting-started/caching): Learn how to cache data and UI in Next.js
- [Migrating to Cache Components](/docs/app/guides/migrating-to-cache-components): Learn how to migrate from route segment configs to Cache Components in Next.js.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/docs/llms.txt](/docs/llms.txt)