Commit 4da7406f authored by Joseph's avatar Joseph Committed by Jiachi Liu

docs: getting started updates 01 (#85750)

parent 40bafdc7
...@@ -232,14 +232,23 @@ Like Server Actions, arguments to cached functions must be serializable. This me ...@@ -232,14 +232,23 @@ Like Server Actions, arguments to cached functions must be serializable. This me
You can accept unserializable values as arguments as long as you don't introspect them. However, you can return them. This allows patterns like cached components that accept Server or Client Components as children: You can accept unserializable values as arguments as long as you don't introspect them. However, you can return them. This allows patterns like cached components that accept Server or Client Components as children:
```tsx filename="app/cached-wrapper.tsx" switcher ```tsx filename="app/cached-wrapper.tsx" switcher
import { ReactNode } from 'react' import type { ReactNode } from 'react'
import { setTimeout } from 'node:timers/promises'
async function getSiteTitle() {
// Simulate a slow database or API call
await setTimeout(1000) // from 'node:timers/promises'
return 'My Website'
}
export async function CachedWrapper({ children }: { children: ReactNode }) { export async function CachedWrapper({ children }: { children: ReactNode }) {
'use cache' 'use cache'
const title = await getSiteTitle()
// Don't introspect children, just pass it through // Don't introspect children, just pass it through
return ( return (
<div className="wrapper"> <div className="wrapper">
<header>Cached Header</header> <h1>{title}</h1>
{children} {children}
</div> </div>
) )
...@@ -247,22 +256,28 @@ export async function CachedWrapper({ children }: { children: ReactNode }) { ...@@ -247,22 +256,28 @@ export async function CachedWrapper({ children }: { children: ReactNode }) {
``` ```
```jsx filename="app/cached-wrapper.js" switcher ```jsx filename="app/cached-wrapper.js" switcher
import { setTimeout } from 'node:timers/promises'
async function getSiteTitle() {
// Simulate a slow database or API call
await setTimeout(1000) // from 'node:timers/promises'
return 'My Website'
}
export async function CachedWrapper({ children }) { export async function CachedWrapper({ children }) {
'use cache' 'use cache'
const title = await getSiteTitle()
// Don't introspect children, just pass it through // Don't introspect children, just pass it through
return ( return (
<div className="wrapper"> <div className="wrapper">
<header>Cached Header</header> <h1>{title}</h1>
{children} {children}
</div> </div>
) )
} }
``` ```
#### Avoid passing dynamic inputs
You must not pass dynamic or runtime data into `use cache` functions unless you avoid introspecting them. Passing values from `cookies()`, `headers()`, or other runtime APIs as arguments will cause errors, as the cache key cannot be determined at pre-render time.
### Tagging and revalidating ### Tagging and revalidating
Tag cached data with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) and revalidate it after mutations using [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions for immediate updates, or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) delay in updates are acceptable. Tag cached data with [`cacheTag`](/docs/app/api-reference/functions/cacheTag) and revalidate it after mutations using [`updateTag`](/docs/app/api-reference/functions/updateTag) in Server Actions for immediate updates, or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) delay in updates are acceptable.
...@@ -521,7 +536,7 @@ export default function Page() { ...@@ -521,7 +536,7 @@ export default function Page() {
### Passing dynamic props ### Passing dynamic props
Components only opt into dynamic rendering when the value is accessed. For example, if you are reading `searchParams` from a `<Page />` component, you can forward this value to another component as a prop: Components that access runtime values like `cookies` or `searchParams` cannot be prerendered. To prerender more of a page's content, you can pass these props down and access their values lower in the tree. For example, if you are reading `searchParams` from a `<Page />` component, you can forward this value to another component as a prop:
```tsx filename="app/page.tsx" switcher ```tsx filename="app/page.tsx" switcher
import { Table, TableSkeleton } from './table' import { Table, TableSkeleton } from './table'
......
...@@ -18,10 +18,11 @@ This page will walk you through how you can fetch data in [Server and Client Com ...@@ -18,10 +18,11 @@ This page will walk you through how you can fetch data in [Server and Client Com
### Server Components ### Server Components
You can fetch data in Server Components using: You can fetch data in Server Components using any asynchronous I/O, such as:
1. The [`fetch` API](#with-the-fetch-api) 1. The [`fetch` API](#with-the-fetch-api)
2. An [ORM or database](#with-an-orm-or-database) 2. An [ORM or database](#with-an-orm-or-database)
3. Reading from the filesystem using Node.js APIs like `fs`
#### With the `fetch` API #### With the `fetch` API
...@@ -285,7 +286,7 @@ To improve the initial load time and user experience, you can use streaming to b ...@@ -285,7 +286,7 @@ To improve the initial load time and user experience, you can use streaming to b
height="785" height="785"
/> />
There are two ways you can implement streaming in your application: There are two ways you can leverage streaming in your application:
1. Wrapping a page with a [`loading.js` file](#with-loadingjs) 1. Wrapping a page with a [`loading.js` file](#with-loadingjs)
2. Wrapping a component with [`<Suspense>`](#with-suspense) 2. Wrapping a component with [`<Suspense>`](#with-suspense)
...@@ -356,7 +357,7 @@ export default function BlogPage() { ...@@ -356,7 +357,7 @@ export default function BlogPage() {
<p>Read the latest posts below.</p> <p>Read the latest posts below.</p>
</header> </header>
<main> <main>
{/* Any content wrapped in a <Suspense> boundary will be streamed */} {/* If there's any dynamic content inside this boundary, it will be streamed in */}
<Suspense fallback={<BlogListSkeleton />}> <Suspense fallback={<BlogListSkeleton />}>
<BlogList /> <BlogList />
</Suspense> </Suspense>
...@@ -380,7 +381,7 @@ export default function BlogPage() { ...@@ -380,7 +381,7 @@ export default function BlogPage() {
<p>Read the latest posts below.</p> <p>Read the latest posts below.</p>
</header> </header>
<main> <main>
{/* Any content wrapped in a <Suspense> boundary will be streamed */} {/* If there's any dynamic content inside this boundary, it will be streamed in */}
<Suspense fallback={<BlogListSkeleton />}> <Suspense fallback={<BlogListSkeleton />}>
<BlogList /> <BlogList />
</Suspense> </Suspense>
...@@ -400,19 +401,9 @@ In development, you can preview and inspect the loading state of your components ...@@ -400,19 +401,9 @@ In development, you can preview and inspect the loading state of your components
### Sequential data fetching ### Sequential data fetching
Sequential data fetching happens when nested components in a tree each fetch their own data and the requests are not [deduplicated](/docs/app/guides/caching#request-memoization), leading to longer response times. Sequential data fetching happens when one request depends on data from another.
<Image For example, `<Playlists>` can only fetch data after `<Artist>` completes because it needs the `artistID`:
alt="Sequential and Parallel Data Fetching"
srcLight="/docs/light/sequential-parallel-data-fetching.png"
srcDark="/docs/dark/sequential-parallel-data-fetching.png"
width="1600"
height="525"
/>
There may be cases where you want this pattern because one fetch depends on the result of the other.
For example, the `<Playlists>` component will only start fetching data once the `<Artist>` component has finished fetching data because `<Playlists>` depends on the `artistID` prop:
```tsx filename="app/artist/[username]/page.tsx" switcher ```tsx filename="app/artist/[username]/page.tsx" switcher
export default async function Page({ export default async function Page({
...@@ -482,7 +473,9 @@ async function Playlists({ artistID }) { ...@@ -482,7 +473,9 @@ async function Playlists({ artistID }) {
} }
``` ```
To improve the user experience, you should use [React `<Suspense>`](/docs/app/getting-started/linking-and-navigating#streaming) to show a `fallback` while data is being fetch. This will enable [streaming](#streaming) and prevent the whole route from being blocked by the sequential data requests. In this example, `<Suspense>` allows the playlists to stream in after the artist data loads. However, the page still waits for the artist data before displaying anything. To prevent this, you can wrap the entire page component in a `<Suspense>` boundary (for example, using a [`loading.js` file](#with-loadingjs)) to show a loading state immediately.
Ensure your data source can resolve the first request quickly, as it blocks everything else. If you can't optimize the request further, consider [caching](#deduplicate-requests-and-cache-data) the result if the data changes infrequently.
### Parallel data fetching ### Parallel data fetching
...@@ -597,11 +590,12 @@ export default async function Page({ ...@@ -597,11 +590,12 @@ export default async function Page({
return isAvailable ? <Item id={id} /> : null return isAvailable ? <Item id={id} /> : null
} }
export const preload = (id: string) => { const preload = (id: string) => {
// void evaluates the given expression and returns undefined // void evaluates the given expression and returns undefined
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void
void getItem(id) void getItem(id)
} }
export async function Item({ id }: { id: string }) { export async function Item({ id }: { id: string }) {
const result = await getItem(id) const result = await getItem(id)
// ... // ...
...@@ -621,11 +615,12 @@ export default async function Page({ params }) { ...@@ -621,11 +615,12 @@ export default async function Page({ params }) {
return isAvailable ? <Item id={id} /> : null return isAvailable ? <Item id={id} /> : null
} }
export const preload = (id) => { const preload = (id) => {
// void evaluates the given expression and returns undefined // void evaluates the given expression and returns undefined
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void
void getItem(id) void getItem(id)
} }
export async function Item({ id }) { export async function Item({ id }) {
const result = await getItem(id) const result = await getItem(id)
// ... // ...
......
...@@ -328,6 +328,38 @@ export function Button() { ...@@ -328,6 +328,38 @@ export function Button() {
} }
``` ```
### Refreshing
After a mutation, you may want to refresh the current page to show the latest data. You can do this by calling [`refresh`](/docs/app/api-reference/functions/refresh) from `next/cache` in a Server Action:
```ts filename="app/lib/actions.ts" switcher
'use server'
import { refresh } from 'next/cache'
export async function updatePost(formData: FormData) {
// Update data
// ...
refresh()
}
```
```js filename="app/lib/actions.js" switcher
'use server'
import { refresh } from 'next/cache'
export async function updatePost(formData) {
// Update data
// ...
refresh()
}
```
This refreshes the client router, ensuring the UI reflects the latest state. The `refresh()` function does not revalidate tagged data. To revalidate tagged data, use [`updateTag`](/docs/app/api-reference/functions/updateTag) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) instead.
### Revalidating ### Revalidating
After performing an update, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function: After performing an update, you can revalidate the Next.js cache and show the updated data by calling [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) within the Server Function:
......
...@@ -25,7 +25,6 @@ refresh(): void; ...@@ -25,7 +25,6 @@ refresh(): void;
'use server' 'use server'
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) { export async function createPost(formData: FormData) {
const title = formData.get('title') const title = formData.get('title')
...@@ -44,7 +43,6 @@ export async function createPost(formData: FormData) { ...@@ -44,7 +43,6 @@ export async function createPost(formData: FormData) {
'use server' 'use server'
import { refresh } from 'next/cache' import { refresh } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData) { export async function createPost(formData) {
const title = formData.get('title') const title = formData.get('title')
......
--- ---
title: mdxRs title: mdxRs
description: Use the new Rust compiler to compile MDX files in the App Router. description: Use the new Rust compiler to compile MDX files in the App Router.
version: experimental. version: experimental
--- ---
For experimental use with `@next/mdx`. Compiles MDX files using the new Rust compiler. For experimental use with `@next/mdx`. Compiles MDX files using the new Rust compiler.
......
...@@ -149,7 +149,7 @@ The following options are available for the `next telemetry` command: ...@@ -149,7 +149,7 @@ The following options are available for the `next telemetry` command:
Learn more about [Telemetry](/telemetry). Learn more about [Telemetry](/telemetry).
### `next typegen` Options ### `next typegen` options
`next typegen` generates TypeScript definitions for your application's routes without performing a full build. This is useful for IDE autocomplete and CI type-checking of route usage. `next typegen` generates TypeScript definitions for your application's routes without performing a full build. This is useful for IDE autocomplete and CI type-checking of route usage.
......
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