Unverified Commit 6fd889b9 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

docs: expand and modernize the Single-Page Applications guide (#95860)

## What

Expands the [Single-Page Applications
guide](https://nextjs.org/docs/app/guides/single-page-applications):

- Adds a full **TanStack Query** section (server prefetch + `dehydrate`
+ client read), alongside the existing SWR and `use()` + Context
patterns
- Makes this guide the **canonical home for the `use()` + Context
pattern**, so it is no longer duplicated across the docs (fetching-data
keeps only the `React.cache` reuse and links here)
- Rewrites the mutations section around one shared reducer with
`useActionState` + `useOptimistic`
- Links a companion runnable demo for every example, and modernizes the
examples (typed `PageProps`/`LayoutProps`, `useSuspenseQuery` vs
`useQuery` guidance, forms/server-actions related guides)

## Why

The guide was outdated and thin on runnable examples, had no real
TanStack Query coverage, and the context + `use()` pattern was
duplicated across several guides.

## How

Each section maps to a runnable demo route. The context pattern is
centralized here as the single source of truth, with fetching-data,
streaming, and authentication linking to it.

Docs-only.
parent 0be0ebe5
...@@ -416,6 +416,8 @@ Your Server Component will now be able to directly render your provider, and all ...@@ -416,6 +416,8 @@ Your Server Component will now be able to directly render your provider, and all
> **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `<html>` document. This makes it easier for Next.js to optimize the static parts of your Server Components. > **Good to know**: You should render providers as deep as possible in the tree – notice how `ThemeProvider` only wraps `{children}` instead of the entire `<html>` document. This makes it easier for Next.js to optimize the static parts of your Server Components.
To pass server-fetched data through context and read it in Client Components with `use()`, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider).
### Third-party components ### Third-party components
When using a third-party component that relies on client-only features, you can wrap it in a Client Component to ensure it works as expected. When using a third-party component that relies on client-only features, you can wrap it in a Client Component to ensure it works as expected.
......
...@@ -2,9 +2,10 @@ ...@@ -2,9 +2,10 @@
title: Fetching Data title: Fetching Data
description: Learn how to fetch data and stream content that depends on data. description: Learn how to fetch data and stream content that depends on data.
related: related:
title: API Reference title: Next steps
description: Learn more about the features mentioned in this page by reading the API Reference. description: Learn more about advanced data-fetching patterns and the features mentioned in this page.
links: links:
- app/guides/single-page-applications
- app/guides/data-security - app/guides/data-security
- app/api-reference/functions/fetch - app/api-reference/functions/fetch
- app/api-reference/file-conventions/loading - app/api-reference/file-conventions/loading
...@@ -313,6 +314,8 @@ export default function Posts({ posts }) { ...@@ -313,6 +314,8 @@ export default function Posts({ posts }) {
In the example above, the `<Posts>` component is wrapped in a [`<Suspense>` boundary](https://react.dev/reference/react/Suspense). This means the fallback will be shown while the promise is being resolved. Learn more about [streaming](#streaming). In the example above, the `<Posts>` component is wrapped in a [`<Suspense>` boundary](https://react.dev/reference/react/Suspense). This means the fallback will be shown while the promise is being resolved. Learn more about [streaming](#streaming).
You can resolve a promise on the server with `await` or in a Client Component with `use()`. React covers [when to resolve a Promise in a Server or Client Component](https://react.dev/reference/react/use#resolve-promise-in-server-or-client-component). To share one promise with many Client Components instead of passing it as a prop, provide it through context. See [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider).
#### Community libraries #### Community libraries
You can use a community library like [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/latest) to fetch data in Client Components. These libraries have their own semantics for caching, streaming, and other features. For example, with SWR: You can use a community library like [SWR](https://swr.vercel.app/) or [React Query](https://tanstack.com/query/latest) to fetch data in Client Components. These libraries have their own semantics for caching, streaming, and other features. For example, with SWR:
...@@ -538,11 +541,9 @@ export default async function Page({ params }) { ...@@ -538,11 +541,9 @@ export default async function Page({ params }) {
> **Good to know:** If one request fails when using `Promise.all`, the entire operation will fail. To handle this, you can use the [`Promise.allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) method instead. > **Good to know:** If one request fails when using `Promise.all`, the entire operation will fail. To handle this, you can use the [`Promise.allSettled`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) method instead.
### Sharing data with context and `React.cache` ### Reusing data with `React.cache`
You can share fetched data across both Server and Client Components by combining [`React.cache`](https://react.dev/reference/react/cache) with context providers.
Create a cached function that fetches data: Wrap a data-fetching function in [`React.cache`](https://react.dev/reference/react/cache) so multiple components in the same request share one result instead of refetching:
```ts filename="app/lib/user.ts" switcher ```ts filename="app/lib/user.ts" switcher
import { cache } from 'react' import { cache } from 'react'
...@@ -562,144 +563,7 @@ export const getUser = cache(async () => { ...@@ -562,144 +563,7 @@ export const getUser = cache(async () => {
}) })
``` ```
Create a context provider that stores the promise: Server Components can call `getUser()` directly:
```tsx filename="app/user-provider.tsx" switcher
'use client'
import { createContext } from 'react'
type User = {
id: string
name: string
}
export const UserContext = createContext<Promise<User> | null>(null)
export default function UserProvider({
children,
userPromise,
}: {
children: React.ReactNode
userPromise: Promise<User>
}) {
return <UserContext value={userPromise}>{children}</UserContext>
}
```
```jsx filename="app/user-provider.js" switcher
'use client'
import { createContext } from 'react'
export const UserContext = createContext(null)
export default function UserProvider({ children, userPromise }) {
return <UserContext value={userPromise}>{children}</UserContext>
}
```
In a layout, pass the promise to the provider without awaiting:
```tsx filename="app/layout.tsx" switcher
import UserProvider from './user-provider'
import { getUser } from './lib/user'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
const userPromise = getUser() // Don't await
return (
<html>
<body>
<UserProvider userPromise={userPromise}>{children}</UserProvider>
</body>
</html>
)
}
```
```jsx filename="app/layout.js" switcher
import UserProvider from './user-provider'
import { getUser } from './lib/user'
export default function RootLayout({ children }) {
const userPromise = getUser() // Don't await
return (
<html>
<body>
<UserProvider userPromise={userPromise}>{children}</UserProvider>
</body>
</html>
)
}
```
Client Components use [`use()`](https://react.dev/reference/react/use) to resolve the promise from context, wrapped in `<Suspense>` for fallback UI:
```tsx filename="app/ui/profile.tsx" switcher
'use client'
import { use, useContext } from 'react'
import { UserContext } from '../user-provider'
export function Profile() {
const userPromise = useContext(UserContext)
if (!userPromise) {
throw new Error('useContext must be used within a UserProvider')
}
const user = use(userPromise)
return <p>Welcome, {user.name}</p>
}
```
```jsx filename="app/ui/profile.js" switcher
'use client'
import { use, useContext } from 'react'
import { UserContext } from '../user-provider'
export function Profile() {
const userPromise = useContext(UserContext)
if (!userPromise) {
throw new Error('useContext must be used within a UserProvider')
}
const user = use(userPromise)
return <p>Welcome, {user.name}</p>
}
```
```tsx filename="app/page.tsx" switcher
import { Suspense } from 'react'
import { Profile } from './ui/profile'
export default function Page() {
return (
<Suspense fallback={<div>Loading profile...</div>}>
<Profile />
</Suspense>
)
}
```
```jsx filename="app/page.js" switcher
import { Suspense } from 'react'
import { Profile } from './ui/profile'
export default function Page() {
return (
<Suspense fallback={<div>Loading profile...</div>}>
<Profile />
</Suspense>
)
}
```
Server Components can also call `getUser()` directly:
```tsx filename="app/dashboard/page.tsx" switcher ```tsx filename="app/dashboard/page.tsx" switcher
import { getUser } from '../lib/user' import { getUser } from '../lib/user'
......
...@@ -523,7 +523,7 @@ function SlugHeading({ slug }: { slug: string }) { ...@@ -523,7 +523,7 @@ function SlugHeading({ slug }: { slug: string }) {
Now `<Sidebar />`, `{children}`, and the Suspense fallback are all part of the static shell. Only `SlugHeading` streams in at request time. You can also pass the entire `params` promise and await it in the child component. Now `<Sidebar />`, `{children}`, and the Suspense fallback are all part of the static shell. Only `SlugHeading` streams in at request time. You can also pass the entire `params` promise and await it in the child component.
The same principle applies to `cookies()`, `headers()`, `searchParams`, and data fetches. See [Sharing data with context and `React.cache`](/docs/app/getting-started/fetching-data#sharing-data-with-context-and-reactcache) for a related pattern. The same principle applies to `cookies()`, `headers()`, `searchParams`, and data fetches. See [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache) for a related pattern.
### Instant navigation ### Instant navigation
......
...@@ -1361,7 +1361,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across ...@@ -1361,7 +1361,7 @@ Session and user data often appear in shell UI (header, nav) that repeats across
If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern. If only part of the shell needs session data (for example, a user menu), move the `await` into a nested Server Component and wrap it in `<Suspense>` so the rest of the page streams first. See [Push dynamic access down](/docs/app/guides/streaming#push-dynamic-access-down) for the pattern.
Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a [Context Provider](#context-providers). To share data across multiple Server Components without re-fetching, see [Sharing data with context and `React.cache`](/docs/app/getting-started/fetching-data#sharing-data-with-context-and-reactcache). Client Components can't import the DAL. Run `verifySession()`, `getUser()`, or similar in a parent Server Component, then pass data to client children as props or through a [Context Provider](#context-providers). To share data across multiple Server Components without re-fetching, see [Reusing data with `React.cache`](/docs/app/getting-started/fetching-data#reusing-data-with-reactcache).
#### Auth checks in page components #### Auth checks in page components
...@@ -1600,6 +1600,8 @@ export default function Profile() { ...@@ -1600,6 +1600,8 @@ export default function Profile() {
If session data is needed in Client Components (e.g. for client-side data fetching), use React’s [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to prevent sensitive session data from being exposed to the client. If session data is needed in Client Components (e.g. for client-side data fetching), use React’s [`taintUniqueValue`](https://react.dev/reference/react/experimental_taintUniqueValue) API to prevent sensitive session data from being exposed to the client.
For the general pattern of passing server-fetched data through context and reading it with `use()`, see [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider).
</AppOnly> </AppOnly>
<PagesOnly> <PagesOnly>
......
...@@ -477,7 +477,7 @@ export default function Layout({ children }: { children: React.ReactNode }) { ...@@ -477,7 +477,7 @@ export default function Layout({ children }: { children: React.ReactNode }) {
} }
``` ```
See [Sharing data with context and React.cache](/docs/app/getting-started/fetching-data#sharing-data-with-context-and-reactcache) for the full pattern including the provider and consumer components. See [Using React's `use` within a Context Provider](/docs/app/guides/single-page-applications#using-reacts-use-within-a-context-provider) for the full pattern.
## Streaming in Route Handlers ## Streaming in Route Handlers
......
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