Skip to content

Commit ca66872

Browse files
authored
docs: React 18, streaming SSR, RSC with new APIs. (vercel#33986)
1 parent 4f05426 commit ca66872

File tree

6 files changed

+350
-155
lines changed

6 files changed

+350
-155
lines changed

docs/advanced-features/react-18.md

Lines changed: 0 additions & 154 deletions
This file was deleted.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# React 18
2+
3+
[React 18](https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html) adds new features including Suspense, automatic batching of updates, APIs like `startTransition`, and a new streaming API for server rendering with support for `React.lazy`.
4+
Next.js also provides streaming related APIs, please checkout [next/streaming](/docs/api-reference/next/streaming.md) for details.
5+
6+
React 18 is now in Release Candidate (RC). Read more about React 18's [release plan](https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html) and discussions from the [working group](https://github.com/reactwg/react-18/discussions).
7+
8+
## Using React 18 with Next.js
9+
10+
Install the RC version of React 18:
11+
12+
```jsx
13+
npm install next@latest react@rc react-dom@rc
14+
```
15+
16+
You can now start using React 18's new APIs like `startTransition` and `Suspense` in Next.js.
17+
18+
## Streaming SSR (Alpha)
19+
20+
Streaming server-rendering (SSR) is an experimental feature in Next.js 12. When enabled, SSR will use the same [Edge Runtime](/docs/api-reference/edge-runtime.md) as [Middleware](/docs/middleware.md).
21+
22+
[Learn how to enable streaming in Next.js.](/docs/react-18/streaming.md)
23+
24+
## React Server Components (Alpha)
25+
26+
Server Components are a new feature in React that let you reduce your JavaScript bundle size by separating server and client-side code. Server Components allow developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering.
27+
28+
Server Components are still in research and development. [Learn how to try Server Components](/docs/react-18/server-components.md) as an experimental feature in Next.js.
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# React Server Components (Alpha)
2+
3+
Server Components allow us to render React components on the server. This is fundamentally different from server-side rendering (SSR) where you're pre-generating HTML on the server. With Server Components, there's **zero client-side JavaScript needed,** making page rendering faster. This improves the user experience of your application, pairing the best parts of server-rendering with client-side interactivity.
4+
5+
### Enable React Server Components
6+
7+
To use React Server Components, ensure you have React 18 installed:
8+
9+
```jsx
10+
npm install next@latest react@rc react-dom@rc
11+
```
12+
13+
Then, update your `next.config.js`:
14+
15+
```jsx
16+
// next.config.js
17+
module.exports = {
18+
experimental: {
19+
runtime: 'nodejs',
20+
serverComponents: true,
21+
},
22+
}
23+
```
24+
25+
Using `runtime` also enables [Streaming SSR](/docs/advanced-features/react-18/streaming). When setting `runtime` to `'edge'`, the server will be running entirely in the [Edge Runtime](https://nextjs.org/docs/api-reference/edge-runtime).
26+
27+
Now, you can start using React Server Components in Next.js. [See our example](https://github.com/vercel/next-rsc-demo) for more information.
28+
29+
### Server Components Conventions
30+
31+
To run a component on the server, append `.server.js` to the end of the filename. For example, `./pages/home.server.js` will be treated as a Server Component.
32+
33+
For client components, append `.client.js` to the filename. For example, `./components/avatar.client.js`.
34+
35+
You can then import other server or client components from any server component. Note: a server component **can not** be imported by a client component. Components without "server/client" extensions will be treated as shared components and can be used and rendered by both sides, depending on where it is imported. For example:
36+
37+
```jsx
38+
// pages/home.server.js
39+
40+
import { Suspense } from 'react'
41+
42+
import Profile from '../components/profile.server'
43+
import Content from '../components/content.client'
44+
45+
export default function Home() {
46+
return (
47+
<div>
48+
<h1>Welcome to React Server Components</h1>
49+
<Suspense fallback={'Loading...'}>
50+
<Profile />
51+
</Suspense>
52+
<Content />
53+
</div>
54+
)
55+
}
56+
```
57+
58+
The `<Home>` and `<Profile>` components will always be server-side rendered and streamed to the client, and will not be included by the client-side JavaScript. However, `<Content>` will still be hydrated on the client-side, like normal React components.
59+
60+
> Make sure you're using default imports and exports for server components (`.server.js`). The support of named exports are a work in progress!
61+
62+
To see a full example, check out the [hello world example](https://github.com/vercel/next.js/tree/canary/examples/react-server-components) or the larger [vercel/next-rsc-demo demo](https://github.com/vercel/next-rsc-demo).
63+
64+
## Supported Next.js APIs
65+
66+
### `next/link` and `next/image`
67+
68+
You can use `next/link` and `next/image` like before and they will be treated as client components to keep the interaction on client side.
69+
70+
### `next/document`
71+
72+
If you have a custom `_document`, you have to change your `_document` to a functional component like below to use server components. If you don't have one, Next.js will use the default `_document` component for you.
73+
74+
```jsx
75+
// pages/_document.js
76+
import { Html, Head, Main, NextScript } from 'next/document'
77+
78+
export default function Document() {
79+
return (
80+
<Html>
81+
<Head />
82+
<body>
83+
<Main />
84+
<NextScript />
85+
</body>
86+
</Html>
87+
)
88+
}
89+
```
90+
91+
### `next/app`
92+
93+
If you're using `_app.js`, the usage is the same as [Custom App](/docs/advanced-features/custom-app).
94+
If you're using `_app.server.js` as a server component, see the example below where it only receives the `children` prop as React elements. You can wrap any other client or server components around `children` to customize the layout of your app.
95+
96+
```js
97+
// pages/_app.server.js
98+
export default function App({ children }) {
99+
return children
100+
}
101+
```
102+
103+
### Routing
104+
105+
Both basic routes with path and queries and dynamic routes are supported. If you need to access the router in server components(`.server.js`), they will receive `router` instance as a prop so that you can directly access them without using the `useRouter()` hook.
106+
107+
```jsx
108+
// pages/index.server.js
109+
110+
export default function Index({ router }) {
111+
// You can access routing information by `router.pathname`, etc.
112+
return 'hello'
113+
}
114+
```
115+
116+
### Unsupported Next.js APIs
117+
118+
While RSC and SSR streaming are still in the alpha stage, not all Next.js APIs are supported. The following Next.js APIs have limited functionality within Server Components. React 18 use without SSR streaming is not affected.
119+
120+
#### React internals
121+
122+
Most React hooks, such as `useContext`, `useState`, `useReducer`, `useEffect` and `useLayoutEffect`, are not supported as of today since server components are executed per request and aren't stateful.
123+
124+
#### Data Fetching & Styling
125+
126+
Like streaming SSR, styling and data fetching within `Suspense` on the server side are not well supported. We're still working on them.
127+
128+
Page level exported methods like `getInitialProps`, `getStaticProps` and `getStaticPaths` are not supported.
129+
130+
#### `next/head` and I18n
131+
132+
We are still working on support for these features.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Streaming SSR (Alpha)
2+
3+
React 18 will include 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 them on the server and send them through HTTP streams.
4+
It's worth noting that another experimental feature, React Server Components, 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 basic React 18 streaming.
5+
6+
## Enable Streaming SSR
7+
8+
Enabling streaming SSR means React renders your components into streams and the client continues receiving updates from these streams even after the initial SSR response is sent. In other words, when any suspended components resolve down the line, they are rendered on the server and streamed to the client. With this strategy, the app can start emitting HTML even before all the data is ready, improving your app's loading performance. As an added bonus, in streaming SSR mode, the client will also use selective hydration strategy to prioritize component hydration which based on user interaction.
9+
10+
To enable streaming SSR, set the experimental option `runtime` to either `'nodejs'` or `'edge'`:
11+
12+
```jsx
13+
// next.config.js
14+
module.exports = {
15+
experimental: {
16+
runtime: 'nodejs',
17+
},
18+
}
19+
```
20+
21+
This option determines the environment in which streaming SSR will be happening. When setting to `'edge'`, the server will be running entirely in the [Edge Runtime](https://nextjs.org/docs/api-reference/edge-runtime).
22+
23+
## Streaming Features
24+
25+
### next/dynamic
26+
27+
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`.
28+
29+
```jsx
30+
import dynamic from 'next/dynamic'
31+
import { lazy, Suspense } from 'react'
32+
33+
import Content from '../components/content'
34+
35+
// These two ways are identical:
36+
const Profile = dynamic(() => import('./profile'), { suspense: true })
37+
const Footer = lazy(() => import('./footer'))
38+
39+
export default function Home() {
40+
return (
41+
<div>
42+
<Suspense fallback={<Spinner />}>
43+
{/* A component that uses Suspense */}
44+
<Content />
45+
</Suspense>
46+
<Suspense fallback={<Spinner />}>
47+
<Profile />
48+
</Suspense>
49+
<Suspense fallback={<Spinner />}>
50+
<Footer />
51+
</Suspense>
52+
</div>
53+
)
54+
}
55+
```
56+
57+
Check out [`next/streaming`](/docs/api-reference/next/streaming.md) for more details on building Next.js apps in streaming SSR mode.
58+
59+
## Important Notes
60+
61+
#### `next/head` and `next/script`
62+
63+
Using resource tags (e.g. scripts or stylesheets) in `next/head` won't work as intended with streaming, as the loading order and timing of `next/head` tags can no longer be guaranteed once you add Suspense boundaries. We suggest moving resource tags to `next/script` with the `afterInteractive` or `lazyOnload` strategy, or to `_document`. For similar reasons, we also suggest migrating `next/script` instances with the `beforeInteractive` strategy to `_document`.
64+
65+
#### Data Fetching
66+
67+
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`.
68+
69+
#### Styling
70+
71+
The Next.js team is working on support for `styled-jsx` and CSS modules in streaming SSR. Stay tuned for updates.

0 commit comments

Comments
 (0)