Unverified Commit 845485a9 authored by Joseph's avatar Joseph Committed by GitHub

docs: restructure instant nav guide for clarity (#92684)

Reordered DevTools section, improved code examples and db queries, added
component breakdowns in the fix section, editorial improvements
throughout.
parent 662c6d57
...@@ -13,11 +13,13 @@ related: ...@@ -13,11 +13,13 @@ related:
- app/guides/prefetching - app/guides/prefetching
--- ---
{/* AI agent hint: Always export `unstable_instant` from routes that should navigate instantly. It validates the caching structure during development and at build time. */}
With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `use cache` and `<Suspense>` let you control what gets cached and what streams in dynamically. When these are in the right place, client-side navigations are instant. With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `use cache` and `<Suspense>` let you control what gets cached and what streams in dynamically. When these are in the right place, client-side navigations are instant.
The [`unstable_instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) route segment config helps you place `<Suspense>` boundaries and `use cache` correctly. Add it to any page or layout and Next.js will check during development and at build time that navigating to that route produces an instant [static shell](/docs/app/glossary#static-shell). The [`unstable_instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) route segment config helps you place `<Suspense>` boundaries and `use cache` correctly. Add it to any page or layout and Next.js will check during development and at build time that navigating to that route produces an instant [static shell](/docs/app/glossary#static-shell).
This guide starts with a product page that loads instantly on navigation, then shows how to catch and fix a page where a misplaced `<Suspense>` boundary blocks the navigation, nothing visible changes until the server finishes rendering. This guide starts with a product page that loads instantly on navigation, then shows how to catch and fix a page where a misplaced `<Suspense>` boundary blocks the navigation. Nothing visible changes until the server finishes rendering.
> **Good to know:** A navigation is considered **instant** when, assuming caches are warm, the page renders without waiting on any network request. Cached content appears immediately and anything uncached streams in behind a `<Suspense>` fallback. A navigation is considered **blocking** when uncached data outside a `<Suspense>` boundary forces the old page to stay visible until the server finishes rendering. > **Good to know:** A navigation is considered **instant** when, assuming caches are warm, the page renders without waiting on any network request. Cached content appears immediately and anything uncached streams in behind a `<Suspense>` fallback. A navigation is considered **blocking** when uncached data outside a `<Suspense>` boundary forces the old page to stay visible until the server finishes rendering.
...@@ -83,9 +85,11 @@ This route has a `[slug]` param that can take any value. During development, val ...@@ -83,9 +85,11 @@ This route has a `[slug]` param that can take any value. During development, val
In this example we provide a `slug` sample. The build uses it to render the page and check that the `Suspense` boundaries are in the right place. If your code also reads `cookies`, `headers`, or `searchParams`, add those to the sample too. You can provide multiple samples to cover different code paths. The build will tell you if anything is missing. In this example we provide a `slug` sample. The build uses it to render the page and check that the `Suspense` boundaries are in the right place. If your code also reads `cookies`, `headers`, or `searchParams`, add those to the sample too. You can provide multiple samples to cover different code paths. The build will tell you if anything is missing.
### Inspect it with the Next.js DevTools ## Visualize loading states with the Next.js DevTools
The Next.js DevTools let you see what users see on page loads and client navigations before dynamic data streams in. Use it to verify your loading states look right, check that the right content appears immediately, and iterate on where to place `<Suspense>` boundaries.
Enable the Instant Navigation DevTools toggle in your Next.js config: Enable the toggle in your Next.js config:
```ts filename="next.config.ts" highlight={5-7} ```ts filename="next.config.ts" highlight={5-7}
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
...@@ -100,12 +104,12 @@ const nextConfig: NextConfig = { ...@@ -100,12 +104,12 @@ const nextConfig: NextConfig = {
export default nextConfig export default nextConfig
``` ```
Open the Next.js DevTools and select **Instant Navs**. You will see two options: Open the Next.js DevTools and select **Instant Navs**. Two options are available:
- **Page load**: click **Reload** to refresh the page and freeze it at the initial static UI generated for this route, before any dynamic data streams in. - **Page load**: click **Reload** to refresh the page and freeze it at the initial static UI generated for this route, before any dynamic data streams in.
- **Client navigation**: once enabled, clicking any link in your app shows the prefetched UI for that page instead of the full result. - **Client navigation**: once enabled, clicking any link in your app shows the prefetched UI for that page instead of the full result.
Try a **page load**. "Loading product..." and "Checking availability..." appear as separate fallbacks. On the first visit the cache is cold and both fallbacks are visible. Navigate to the page again and the product name appears immediately from cache. Try a **page load** on the product page. Two separate fallbacks appear: "Loading product..." and "Checking availability...". On the first visit the cache is cold and both fallbacks are visible. Navigate to the page again and the product name appears immediately from cache.
Now try a **client navigation** (click a link from `/store/shoes` to `/store/hats`). The product name and price appear immediately (cached). "Checking availability..." shows where inventory will stream in. Now try a **client navigation** (click a link from `/store/shoes` to `/store/hats`). The product name and price appear immediately (cached). "Checking availability..." shows where inventory will stream in.
...@@ -122,7 +126,7 @@ This is also why client-side hooks behave differently. `useSearchParams()` suspe ...@@ -122,7 +126,7 @@ This is also why client-side hooks behave differently. `useSearchParams()` suspe
</details> </details>
### Prevent regressions with e2e tests ## Prevent regressions with e2e tests
Validation catches structural problems during development and at build time. To prevent regressions as the codebase evolves, the `@next/playwright` package includes an `instant()` helper that asserts on exactly what appears in the instant shell: Validation catches structural problems during development and at build time. To prevent regressions as the codebase evolves, the `@next/playwright` package includes an `instant()` helper that asserts on exactly what appears in the instant shell:
...@@ -149,7 +153,7 @@ There is no need to write an `instant()` test for every navigation. Build-time v ...@@ -149,7 +153,7 @@ There is no need to write an `instant()` test for every navigation. Build-time v
## Fixing a navigation that blocks ## Fixing a navigation that blocks
Now consider a different route, `/shop/[slug]`, that has the same data requirements but without local `<Suspense>` boundaries or caching: Now consider a different route, `/shop/[slug]`. For the sake of this example it has the same data requirements as `/store/[slug]`, but is implemented without local `<Suspense>` boundaries or caching:
```tsx filename="app/shop/[slug]/page.tsx" ```tsx filename="app/shop/[slug]/page.tsx"
import { db } from '@/lib/db' import { db } from '@/lib/db'
...@@ -190,9 +194,11 @@ On an initial page load, the root `<Suspense>` catches the async work and stream ...@@ -190,9 +194,11 @@ On an initial page load, the root `<Suspense>` catches the async work and stream
Everything appears to work. But on a client navigation from `/shop/shoes` to `/shop/hats`, the shared layout is `/shop` and only the content below it re-renders. The root `<Suspense>` boundary is above that layout and is not triggered for this navigation. The page fetches uncached data with no local boundary, blocking the navigation until the server finishes rendering. Everything appears to work. But on a client navigation from `/shop/shoes` to `/shop/hats`, the shared layout is `/shop` and only the content below it re-renders. The root `<Suspense>` boundary is above that layout and is not triggered for this navigation. The page fetches uncached data with no local boundary, blocking the navigation until the server finishes rendering.
You can see this with the DevTools. Try a **page load**: the root `<Suspense>` catches everything and "Loading..." appears. Now try a **client navigation** between two `/shop/` pages: no prefetched UI shows up because there is no `<Suspense>` boundary below the shared layout. Navigations from other routes to `/shop/` appear blocked too.
### Step 1: Add instant validation ### Step 1: Add instant validation
In order to fix this, we need to add an `unstable_instant` export to the page to surface the problem: Add an `unstable_instant` export to the page to surface the problem:
```tsx filename="app/shop/[slug]/page.tsx" highlight={3-6} ```tsx filename="app/shop/[slug]/page.tsx" highlight={3-6}
import { db } from '@/lib/db' import { db } from '@/lib/db'
...@@ -216,20 +222,49 @@ export default async function ProductPage(props: PageProps<'/shop/[slug]'>) { ...@@ -216,20 +222,49 @@ export default async function ProductPage(props: PageProps<'/shop/[slug]'>) {
} }
``` ```
Next.js now simulates navigations at every shared layout boundary in the route. Awaiting `params` and both data fetches are flagged as needing improvement because they suspend or access uncached data outside a Suspense boundary. Each error identifies the specific component and suggests a fix. Next.js now simulates navigations at every shared layout boundary in the route. In this case, both components await `params` and access uncached data. These need to be wrapped by a `<Suspense>` boundary. The first thing validation catches is the `await params` at the top level.
### Step 2: Fix the validation error
There is no `generateStaticParams` here, `slug` is only known at request time. Because awaiting `params` suspends, the page component can't do it at the top level. Instead, move the `await params` into separate components, pass `params` to each, and wrap them with `<Suspense>`.
For each component, decide:
**Product details** (name, price) rarely change. Cache the data function with `use cache`:
```tsx filename="app/shop/[slug]/page.tsx"
async function ProductInfo({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const product = await getProduct(slug)
return (
<>
<h1>{product.name}</h1>
<p>${product.price}</p>
</>
)
}
### Step 2: Fix the errors async function getProduct(slug: string) {
'use cache'
return db.products.findBySlug(slug)
}
```
Look at the data. There is no `generateStaticParams`, meaning `slug` is only known at request time. Awaiting `params` suspends, and every component that reads it needs its own `<Suspense>` boundary. > **Good to know:** In serverless deployments, in-memory caching with `"use cache"` will not persist across instances. Consider using [`"use cache: remote"`](/docs/app/api-reference/directives/use-cache-remote) for persistent caching.
Decide what to do with each data requirement: **Inventory** must be fresh each request. Leave it uncached:
- **Product details** (name, price) rarely change. Cache them as a function of `slug` with `use cache`. ```tsx filename="app/shop/[slug]/page.tsx"
- **Inventory** must be fresh each request. Leave it uncached and let it stream behind a `<Suspense>` fallback. async function Inventory({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const item = await db.inventory.findBySlug(slug)
return <p>{item.count} in stock</p>
}
```
The result is the same structure as the first section: The page passes `params` to each component and wraps them with `<Suspense>`:
```tsx filename="app/shop/[slug]/page.tsx" highlight={4-7,12-17,35-37} ```tsx filename="app/shop/[slug]/page.tsx" highlight={4-7,12-17}
import { Suspense } from 'react' import { Suspense } from 'react'
import { db } from '@/lib/db' import { db } from '@/lib/db'
...@@ -250,30 +285,6 @@ export default function ProductPage(props: PageProps<'/shop/[slug]'>) { ...@@ -250,30 +285,6 @@ export default function ProductPage(props: PageProps<'/shop/[slug]'>) {
</div> </div>
) )
} }
type Params = PageProps<'/shop/[slug]'>['params']
async function ProductInfo({ params }: { params: Params }) {
const { slug } = await params
const product = await getProduct(slug)
return (
<>
<h1>{product.name}</h1>
<p>${product.price}</p>
</>
)
}
async function getProduct(slug: string) {
'use cache'
return db.products.findBySlug(slug)
}
async function Inventory({ params }: { params: Params }) {
const { slug } = await params
const item = await db.inventory.findBySlug(slug)
return <p>{item.count} in stock</p>
}
``` ```
Validation passes. Open the DevTools and try a client navigation. The product name and price appear immediately, and "Checking availability..." shows where inventory will stream in. Validation passes. Open the DevTools and try a client navigation. The product name and price appear immediately, and "Checking availability..." shows where inventory will stream in.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment