Unverified Commit 74162655 authored by Lee Robinson's avatar Lee Robinson Committed by GitHub

Improve `next/dynamic` docs and add links to layouts RFC. (#37244)

- Updates `next/dynamic` docs to teach Suspense first
- Adds links to Layouts RFC in layouts/pages docs
- Clarifies and simplifies streaming docs
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent 566d1020
...@@ -11,169 +11,98 @@ description: Dynamically import JavaScript modules and React Components and spli ...@@ -11,169 +11,98 @@ description: Dynamically import JavaScript modules and React Components and spli
</ul> </ul>
</details> </details>
Next.js supports ES2020 [dynamic `import()`](https://github.com/tc39/proposal-dynamic-import) for JavaScript. With it you can import JavaScript modules dynamically and work with them. They also work with SSR. Next.js supports lazy loading external libraries with `import()` and React components with `next/dynamic`. Deferred loading helps improve the initial loading performance by decreasing the amount of JavaScript necessary to render the page. Components or libaries are only imported and included in the JavaScript bundle when they're used.
In the following example, we implement fuzzy search using `fuse.js` and only load the module dynamically in the browser after the user types in the search input: `next/dynamic` is an extension of [`React.lazy`](https://reactjs.org/docs/code-splitting.html#reactlazy). When used in combination with [`Suspense`](https://reactjs.org/docs/react-api.html#reactsuspense), components can delay hydration until the Suspense boundary is resolved.
```jsx ## Example
import { useState } from 'react'
const names = ['Tim', 'Joe', 'Bel', 'Max', 'Lee']
export default function Page() {
const [results, setResults] = useState()
return (
<div>
<input
type="text"
placeholder="Search"
onChange={async (e) => {
const { value } = e.currentTarget
// Dynamically load fuse.js
const Fuse = (await import('fuse.js')).default
const fuse = new Fuse(names)
setResults(fuse.search(value))
}}
/>
<pre>Results: {JSON.stringify(results, null, 2)}</pre>
</div>
)
}
```
You can think of dynamic imports as another way to split your code into manageable chunks.
React components can also be imported using dynamic imports, but in this case we use it in conjunction with `next/dynamic` to make sure it works like any other React Component. Check out the sections below for more details on how it works. By using `next/dynamic`, the header component will not be included in page's the initial JavaScript bundle. The page will render the Suspense `fallback` first, followed by the `Header` component when the `Suspense` boundary is resolved.
## Basic usage
In the following example, the module `../components/hello` will be dynamically loaded by the page:
```jsx ```jsx
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
import { Suspense } from 'react'
const DynamicComponent = dynamic(() => import('../components/hello')) const DynamicHeader = dynamic(() => import('../components/header'), {
suspense: true,
})
function Home() { export default function Home() {
return ( return (
<div> <Suspense fallback={`Loading...`}>
<Header /> <DynamicHeader />
<DynamicComponent /> </Suspense>
<p>HOME PAGE is here!</p>
</div>
) )
} }
export default Home
``` ```
`DynamicComponent` will be the default component returned by `../components/hello`. It works like a regular React Component, and you can pass props to it as you normally would.
> **Note**: In `import('path/to/component')`, the path must be explicitly written. It can't be a template string nor a variable. Furthermore the `import()` has to be inside the `dynamic()` call for Next.js to be able to match webpack bundles / module ids to the specific `dynamic()` call and preload them before rendering. `dynamic()` can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar to `React.lazy`. > **Note**: In `import('path/to/component')`, the path must be explicitly written. It can't be a template string nor a variable. Furthermore the `import()` has to be inside the `dynamic()` call for Next.js to be able to match webpack bundles / module ids to the specific `dynamic()` call and preload them before rendering. `dynamic()` can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar to `React.lazy`.
If you are not using React 18, you can use the `loading` attribute in place of the Suspense `fallback`.
```jsx
const DynamicHeader = dynamic(() => import('../components/header'), {
loading: () => <header />,
})
```
## With named exports ## With named exports
If the dynamic component is not the default export, you can use a named export too. Consider the module `../components/hello.js` which has a named export `Hello`: To dynamically import a named export, you can return it from the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`import()`](https://github.com/tc39/proposal-dynamic-import#example):
```jsx ```jsx
// components/hello.js
export function Hello() { export function Hello() {
return <p>Hello!</p> return <p>Hello!</p>
} }
```
To dynamically import the `Hello` component, you can return it from the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by [`import()`](https://github.com/tc39/proposal-dynamic-import#example), like so:
```jsx // pages/index.js
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => const DynamicComponent = dynamic(() =>
import('../components/hello').then((mod) => mod.Hello) import('../components/hello').then((mod) => mod.Hello)
) )
function Home() {
return (
<div>
<Header />
<DynamicComponent />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
```
## With custom loading component
An optional `loading` component can be added to render a loading state while the dynamic component is being loaded. For example:
```jsx
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello'),
{ loading: () => <p>...</p> }
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithCustomLoading />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
``` ```
## With no SSR ## With no SSR
You may not always want to include a module on server-side. For example, when the module includes a library that only works in the browser. To dynamically load a component on the client side, you can use the `ssr` option to disable server-rendering. This is useful if an external dependency or component relies on browser APIs like `window`.
Take a look at the following example:
```jsx ```jsx
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic( const DynamicHeader = dynamic(() => import('../components/header'), {
() => import('../components/hello3'), ssr: false,
{ ssr: false } })
)
function Home() {
return (
<div>
<Header />
<DynamicComponentWithNoSSR />
<p>HOME PAGE is here!</p>
</div>
)
}
export default Home
``` ```
## With suspense ## With external libraries
Option `suspense` allows you to lazy-load a component, similar to `React.lazy` and `<Suspense>` with React 18. Note that it only works on client-side or server-side with `fallback`. Full SSR support in concurrent mode is still a work-in-progress. This example uses the external library `fuse.js` for fuzzy search. The module is only loaded in the browser after the user types in the search input.
```jsx ```jsx
import dynamic from 'next/dynamic' import { useState } from 'react'
const DynamicLazyComponent = dynamic(() => import('../components/hello4'), { const names = ['Tim', 'Joe', 'Bel', 'Lee']
suspense: true,
}) export default function Page() {
const [results, setResults] = useState()
function Home() {
return ( return (
<div> <div>
<Suspense fallback={`loading`}> <input
<DynamicLazyComponent /> type="text"
</Suspense> placeholder="Search"
onChange={async (e) => {
const { value } = e.currentTarget
// Dynamically load fuse.js
const Fuse = (await import('fuse.js')).default
const fuse = new Fuse(names)
setResults(fuse.search(value))
}}
/>
<pre>Results: {JSON.stringify(results, null, 2)}</pre>
</div> </div>
) )
} }
......
# Streaming SSR # Streaming SSR
React 18 includes architectural improvements to React server-side rendering (SSR) performance. This means you can use `Suspense` in your React components in streaming SSR mode and React will render content on the server and send updates through HTTP streams. React 18 includes architectural improvements to React server-side rendering (SSR) performance. This means you can use `Suspense` in your React components in streaming SSR mode and React will render content on the server and send updates through HTTP streams.
React Server Components, an experimental feature, is based on streaming. You can read more about Server Components related streaming APIs in [`next/streaming`](/docs/api-reference/next/streaming.md). However, this guide focuses on streaming with React 18. React Server Components, an experimental feature, is based on streaming. You can read more about Server Components related streaming APIs in [`next/streaming`](/docs/api-reference/next/streaming.md). However, this guide focuses on streaming with React 18.
## Using Streaming Server-Rendering ## Using Streaming Server-Rendering
...@@ -11,43 +12,15 @@ All SSR pages have the ability to render components into streams and the client ...@@ -11,43 +12,15 @@ All SSR pages have the ability to render components into streams and the client
As an added bonus, in streaming SSR mode the client will also use selective hydration to prioritize component hydration based on user interactions, further improving performance. As an added bonus, in streaming SSR mode the client will also use selective hydration to prioritize component hydration based on user interactions, further improving performance.
For non-SSR pages, all Suspense boundaries will still be [statically optimized](/docs/advanced-features/automatic-static-optimization.md). For non-SSR pages, all Suspense boundaries will still be [statically optimized](/docs/advanced-features/automatic-static-optimization.md). Check out [`next/streaming`](/docs/api-reference/next/streaming.md) for the API reference for streaming SSR.
## Streaming Features ## Streaming Features
### next/dynamic ### next/dynamic
Dynamic imports through `React.lazy` have better support in React 18. Previously, Next.js supported dynamic imports internally without requiring `Suspense` or `React.lazy`. Now to embrace the official APIs on the React side, we provide you with `options.suspense` in `next/dynamic`. Next.js supports lazy loading external libraries with `import()` and React components with `next/dynamic`. Deferred loading helps improve the initial loading performance by decreasing the amount of JavaScript necessary to render the page. Components or libaries are only imported and included in the JavaScript bundle when they're used.
```jsx Read more about how to use [`next/dynamic`](/docs/advanced-features/dynamic-import.md).
import dynamic from 'next/dynamic'
import { lazy, Suspense } from 'react'
import Content from '../components/content'
// These two ways are identical:
const Profile = dynamic(() => import('./profile'), { suspense: true })
const Footer = lazy(() => import('./footer'))
export default function Home() {
return (
<div>
<Suspense fallback={<Spinner />}>
{/* A component that uses Suspense */}
<Content />
</Suspense>
<Suspense fallback={<Spinner />}>
<Profile />
</Suspense>
<Suspense fallback={<Spinner />}>
<Footer />
</Suspense>
</div>
)
}
```
Check out [`next/streaming`](/docs/api-reference/next/streaming.md) for more details on building Next.js apps in streaming SSR mode.
## Important Notes ## Important Notes
...@@ -57,10 +30,15 @@ Using resource tags (e.g. scripts or stylesheets) in `next/head` won't work as i ...@@ -57,10 +30,15 @@ Using resource tags (e.g. scripts or stylesheets) in `next/head` won't work as i
#### Data Fetching #### Data Fetching
Currently, data fetching within `Suspense` boundaries on the server side is not fully supported, which could lead to mismatching between server and client. In the short-term, please don't try data fetching within `Suspense`. Data fetching within `Suspense` boundaries is currently only supported on the client side. **Server-side data fetching is not supported** yet. Read the [Layouts RFC](https://nextjs.org/blog/layouts-rfc) for more information about the future of data fetching on the server.
#### Styling #### Styling
Inline styles, Global CSS, CSS modules and Next.js built-in `styled-jsx` are supported with streaming. The Next.js team is working on the guide of integrating other CSS-in-JS solutions in streaming SSR. Stay tuned for updates. The following solutions are compatible with Next.js streaming:
- Inline Styles
- [Global Stylesheets](/docs/basic-features/built-in-css-support.md#adding-a-global-stylesheet)
- [CSS Modules](/docs/basic-features/built-in-css-support.md#adding-component-level-css)
- [styled-jsx](/docs/basic-features/built-in-css-support.md#css-in-js)
> Note: The styling code should be only placed in client components, not server components, when using React Server Components CSS-in-JS solutions like `styled-components` and `emotion` are currently not compatible with streaming. For library authors, check out the [upgrade guide](https://github.com/reactwg/react-18/discussions/110) to learn more.
...@@ -11,6 +11,8 @@ description: Learn how to share components and state between Next.js pages with ...@@ -11,6 +11,8 @@ description: Learn how to share components and state between Next.js pages with
</ul> </ul>
</details> </details>
> **Note:** We are introducing improved layouts support in Next.js. Read the [Layouts RFC](https://nextjs.org/blog/layouts-rfc) for more details and to provide feedback.
The React model allows us to deconstruct a [page](/docs/basic-features/pages.md) into a series of components. Many of these components are often reused between pages. For example, you might have the same navigation bar and footer on every page. The React model allows us to deconstruct a [page](/docs/basic-features/pages.md) into a series of components. Many of these components are often reused between pages. For example, you might have the same navigation bar and footer on every page.
```jsx ```jsx
......
...@@ -4,7 +4,7 @@ description: Next.js pages are React Components exported in a file in the pages ...@@ -4,7 +4,7 @@ description: Next.js pages are React Components exported in a file in the pages
# Pages # Pages
> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/pages). > **Note:** We are introducing improved routing support in Next.js. Read the [Layouts RFC](https://nextjs.org/blog/layouts-rfc) for more details and to provide feedback.
In Next.js, a **page** is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the `pages` directory. Each page is associated with a route based on its file name. In Next.js, a **page** is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the `pages` directory. Each page is associated with a route based on its file name.
......
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