Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Rewrite Rendering Section and React Essentials Page #51579

Merged
merged 74 commits into from
Aug 24, 2023
Merged
Show file tree
Hide file tree
Changes from 42 commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
8df9c9d
Recommend foundations course for beginners
delbaoliveira Jun 20, 2023
a21c723
Tentative outline
delbaoliveira Jun 20, 2023
85e4be8
Add RSC page intro
delbaoliveira Jun 20, 2023
3d02944
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Jun 20, 2023
cefc3a9
No code in page titles
delbaoliveira Jun 20, 2023
a2b145d
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Jul 6, 2023
b0c0d66
Brain dump: foundational concepts
delbaoliveira Jul 7, 2023
c060938
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 1, 2023
e180bd0
Change of plans - remove react essentials pages
delbaoliveira Aug 1, 2023
58b9f39
Swap static/dynamic and components page
delbaoliveira Aug 1, 2023
acb9351
Write fundamentals introduction
delbaoliveira Aug 1, 2023
6aba8b8
Write about react rendering environments
delbaoliveira Aug 1, 2023
5e9ad99
Write about Next.js runtimes
delbaoliveira Aug 1, 2023
779a081
Write about rendering strategies
delbaoliveira Aug 1, 2023
1e153d6
Write about the request-response lifecycle
delbaoliveira Aug 1, 2023
4a2b148
Write about the network boundary
delbaoliveira Aug 1, 2023
bb23c01
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 1, 2023
7d541ad
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 2, 2023
d6de31d
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 4, 2023
bfe05da
Move patterns to their own page
delbaoliveira Aug 4, 2023
48f5706
Clean and reshuffle
delbaoliveira Aug 4, 2023
60ded00
Review fundamentals
delbaoliveira Aug 4, 2023
f4da64a
Review fundamentals page
delbaoliveira Aug 7, 2023
d3b6073
hm, not quite there yet
delbaoliveira Aug 7, 2023
e371156
Write about the benefits / use cases for server rendering
delbaoliveira Aug 7, 2023
fa30c9d
Misc
delbaoliveira Aug 7, 2023
db453f1
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 7, 2023
1f8ccc6
Write about using server components in Next.js
delbaoliveira Aug 8, 2023
f55e733
Update docs/02-app/01-building-your-application/03-rendering/index.mdx
delbaoliveira Aug 8, 2023
e857950
Move sections and delete React essentials page
delbaoliveira Aug 8, 2023
f8b2107
Write about building hybrid applications
delbaoliveira Aug 8, 2023
de081b6
Misc
delbaoliveira Aug 8, 2023
d39ce58
Write about how Server Components are rendered
delbaoliveira Aug 8, 2023
505e42a
Add note about data cache being separate from static rendering
delbaoliveira Aug 8, 2023
bccee54
Write client-side rendering outline
delbaoliveira Aug 8, 2023
a894cd6
Merge branch 'docs-react-essentials-revamp' of https://github.com/ver…
delbaoliveira Aug 8, 2023
225477c
Review
delbaoliveira Aug 9, 2023
7ca1f57
Write about streaming
delbaoliveira Aug 9, 2023
962a88c
Client rendering outline + use cases
delbaoliveira Aug 9, 2023
0f2d3a2
Write about "use client"
delbaoliveira Aug 11, 2023
51345c6
Discuss how client components are rendered for initial visit
delbaoliveira Aug 11, 2023
f58cf84
Write about switching back to the server environment
delbaoliveira Aug 11, 2023
5772dec
Update docs/02-app/01-building-your-application/03-rendering/02-clien…
delbaoliveira Aug 11, 2023
edd62b5
Rewrite composition patterns
delbaoliveira Aug 11, 2023
c35d708
Merge branch 'docs-react-essentials-revamp' of https://github.com/ver…
delbaoliveira Aug 11, 2023
013c765
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 11, 2023
64c5ccf
Rename SSR and CSR pages
delbaoliveira Aug 17, 2023
b8c9e85
Rewrite Server Components page
delbaoliveira Aug 17, 2023
cbd9341
Rewrite Client Components page
delbaoliveira Aug 17, 2023
a3df58c
Review composition patterns page
delbaoliveira Aug 17, 2023
12acb6c
Fix some broken links
delbaoliveira Aug 17, 2023
bb0b589
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 17, 2023
fd93a81
💅🏼
delbaoliveira Aug 17, 2023
842e1ec
Remove inaccurate information
delbaoliveira Aug 17, 2023
c2739f5
Fix some broken links
delbaoliveira Aug 17, 2023
6cbf13c
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 17, 2023
d2514d3
Fix more broken links
delbaoliveira Aug 17, 2023
8c99b43
Merge branch 'docs-react-essentials-revamp' of https://github.com/ver…
delbaoliveira Aug 17, 2023
01b9205
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 21, 2023
5362ef5
Update broken links
delbaoliveira Aug 21, 2023
1e9b673
More broken links
delbaoliveira Aug 21, 2023
37d6ce8
Review interleaving client and server components section
delbaoliveira Aug 21, 2023
a94e845
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 21, 2023
bbdbbb9
Remove mention of Date not being serializable
delbaoliveira Aug 21, 2023
de1e03e
Merge branch 'docs-react-essentials-revamp' of https://github.com/ver…
delbaoliveira Aug 21, 2023
2a53544
Update docs/02-app/01-building-your-application/03-rendering/01-serve…
delbaoliveira Aug 21, 2023
a399b52
Apply suggestions from code review
delbaoliveira Aug 22, 2023
1c270ad
Update docs/02-app/01-building-your-application/03-rendering/03-compo…
delbaoliveira Aug 22, 2023
9dd27e0
Apply Michael's feedback
delbaoliveira Aug 23, 2023
8e4836d
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 23, 2023
abff487
Update diagram placeholders
delbaoliveira Aug 24, 2023
92b9a87
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 24, 2023
b768c89
Update broken link from merging into canary
delbaoliveira Aug 24, 2023
866cbcf
Merge branch 'canary' into docs-react-essentials-revamp
delbaoliveira Aug 24, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions docs/01-getting-started/index.mdx

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
---
title: Server-Side Rendering
nav_title: Server-Side Rendering
description: Learn how Server-side Rendering works and its subsets - static and dynamic rendering.
related:
description: Learn how Next.js caches data and the result of static rendering.
links:
- app/building-your-application/caching
---

> In the beginning, there was the server. - _Copilot_

Server-Side Rendering is a strategy for rendering parts of your web application on the server. In Next.js, this is done with [React Server Components](), and the rendering work is split by route segments to enable streaming.

This page will go through how Server Components work, when you might use them, and the three subsets of Server-Side Rendering:

- [Static Rendering](#static-rendering-default)
- [Dynamic Rendering](#dynamic-rendering)
- [Streaming](#streaming)

## React Server Components

React Server Components allow us to write non-interactive UI that can be rendered and cached on the server. There are a couple of benefits to doing the rendering work on the server, including:

- **Data Fetching**: Server Components allow you to move data fetching to the server, closer to your data source. This can improve performance by reducing the time it takes to fetch data needed for rendering.
- **Security**: Server Components allow you to keep sensitive data and logic on the server, such as tokens and API keys, without the risk of exposing them to the client.
- **Caching**: By rendering on the server, the result can be cached and reused on subsequent requests and across users. This can improve performance and reduce cost by reducing the amount of rendering done on each request.
- **Bundle Sizes**: Server Components allow you to keep large dependencies that previously would impact the client JavaScript bundle size on the server. This is beneficial for users with slow internet or less powerful devices, as the client does not have to download and parse any JavaScript for Server Components.
- **Initial Page Load and [First Contentful Paint (FCP)](https://web.dev/fcp/)**: On the server, we can generate HTML to allow users to view the page immediately, without waiting for the client to download and parse JavaScript.
- **SEO**: Search engine bots can use the rendered HTML to crawl and index pages, this can improve your application's SEO.

## Using Server Components in Next.js

By default, the [root layout](/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) of your Next.js application is a Server Component, making its children Server Components as well. This allows you automatically implement server-side rendering with no additional configuration.

> **Why are Server Components the default?**
>
> There are three reasons why Next.js uses Server Components by default:
>
> - During the [request lifecycle](/docs/app/building-your-application/rendering#request-response-lifecycle), you can do data fetching and other computational work on the server before sending the response to the client, reducing the number of requests made to the server from the client.
> - On the server, routes can be [statically rendered](#static-rendering-default) for better performance, this means the rendering work can be done ahead of time and cached.
> - During [dynamic rendering](#dynamic-rendering), the work can be split into chunks and streamed to the client, allowing the user to see a preview of the page before it's fully rendered.

## How are Server Components rendered?

On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks: by individual routes segments and [Suspense Boundaries](https://react.dev/reference/react/Suspense).

Each chunk is rendered in two steps:

1. React renders Server Components into a special data format called the [React Server Component Payload (RSC)]().
2. Next.js uses the RSC Payload and Client Component JavaScript instructions to render **HTML** on the server.

{/* Rendering Diagram */}

After rendering, Next.js caches the rendered RSC Payload and HTML on the server - this is called [static rendering](#static-rendering-default). However, since the rendering work is split by route segments, we don't have to wait for everything to render before caching or sending a response to the client, we can also [stream](#streaming) the chunks as soon as the work is completed - this is called [dynamic rendering](#dynamic-rendering) with [streaming](#streaming).

Finally, on the client:

1. The HTML is used to immediately show a fast non-interactive initial preview of the route.
2. The React Server Components Payload is used to reconcile the Client and Server Component trees, and update the DOM.
3. The JavaScript instructions are used to [hydrate](https://react.dev/reference/react-dom/client/hydrateRoot) Client Components and make the application interactive.

> **What is the React Server Component Payload (RSC)?**
>
> The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:
>
> - The rendered result of Server Components
> - Placeholders for where Client Components should be rendered and references to their JavaScript files
> - Any props passed from a Server Component to a Client Component

## Static, Dynamic, and Streaming Server-Side Rendering

There are three subsets of Server-Side Rendering: Static, Dynamic, and Streaming.

{/* Static Rendering Diagram */}

- **Static Rendering (Default)**: Routes are rendered and cached at **build time** or after [data revalidation](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data). This is an optimization that allows you to serve the cached route instead of rendering content that doesn't change on the server for every request, resulting in faster page loads.

{/* Dynamic Rendering Diagram */}

- **Dynamic Rendering**: Routes are rendered on the server at **request time**. Dynamic rendering is useful when a route has data that is personalized to the user or can only be known at request time, such as a user's cookies or the URL's search params.

{/* Streaming Diagram */}

- **Streaming**: Routes are rendered on the server at **request time**, and the work is split into chunks and streamed to the client as it becomes ready. This allows the user to see a preview of the page before it's fully rendered.

As a developer, you don't need to choose between static and dynamic rendering, Next.js will automatically choose the best rendering strategy for each route based on the features and APIs used. You may choose to stream parts of a route to improve the user experience, this is useful for UI that depends on slower data fetches and would otherwise block rendering of the whole route.

> **Rendering vs. Data Caching**
>
> In Next.js, Static Rendering is separate from Data Caching. A route can be statically or dynamically rendered, and still use cached data. Learn more about [caching](/docs/app/building-your-application/caching#data-cache).

### Switching to Dynamic Rendering

During rendering, if a [dynamic function](#dynamic-functions) or [uncached data request](/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching) is discovered, Next.js will switch to dynamically rendering the whole route. This table summarizes how dynamic functions and data caching affect whether a route is statically or dynamically rendered:

| Route | Dynamic Functions | Data |
| -------------------- | ----------------- | ---------- |
| Statically Rendered | No | Cached |
| Dynamically Rendered | Yes | Cached |
| Dynamic Rendered | No | Not Cached |
| Dynamic Rendered | Yes | Not Cached |

From the table above, for a route to be fully static, all data must be cached. However, you can have a dynamically rendered route that uses both cached and uncached data fetches. This is useful when you have a page that mostly re-uses cached data, but has some uncached data. It allows you to opt into dynamic rendering without worrying about the performance impact of fetching all the data at request time.

### Dynamic Functions

Dynamic functions rely on information that can only be known at request time such as a user's cookies, current requests headers, or the URL's search params. In Next.js, these dynamic functions are:

- **[`cookies()`](/docs/app/api-reference/functions/cookies) and [`headers()`](/docs/app/api-reference/functions/headers)**: Using these in a Server Component will opt the whole route into dynamic rendering at request time.
- **[`useSearchParams()`](/docs/app/api-reference/functions/use-search-params)**:
- In Client Components, it'll skip static rendering and instead render all Client Components up to the nearest parent Suspense boundary on the client.
- We recommend wrapping the Client Component that uses `useSearchParams()` in a `<Suspense/>` boundary. This will allow any Client Components above it to be statically rendered. [Example](/docs/app/api-reference/functions/use-search-params#static-rendering).
- **[`searchParams`](/docs/app/api-reference/file-conventions/page#searchparams-optional)**: Using the [Pages](/docs/app/api-reference/file-conventions/page) prop will opt the page into dynamic rendering at request time.

### Streaming

Streaming allows you to split the rendering work into chunks and send them to the client as they become ready. In Next.js, you can stream route segments using `loading.js`, and UI components with React Suspense. See the [Loading UI and Streaming](/docs/app/building-your-application/routing/loading-ui-and-streaming) docs for more information.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
---
title: Client-Side Rendering (CSR)
nav_title: Client-Side Rendering (CSR)
description: Learn how Client-side Rendering works and how to use Client Components in Next.js.
---

Client-side Rendering is a strategy for rendering parts of your web application on the client. In Next.js, this is done with [React Client Components](). Client-side rendering is also **opt-in**, meaning you have to explicitly decide what components React should render on the client.

This page will go through how Client Components work, when you might use them, and how Next.js optimizes them.

## React Client Components

React Server Components allow us to create interactive UI that is rendered on the client. There are a couple of benefits to doing the rendering work on the client, including:
delbaoliveira marked this conversation as resolved.
Show resolved Hide resolved

- **Interactivity**: Client Components can use state, effects, and event listeners, meaning they can provide immediate feedback to the user and update the UI.
- **Browser APIs**: Client Components have access to browser APIs, like [geolocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) or [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).

## Using Client Components in Next.js

To use Client Components, you can add the React [`"use client"` directive](https://react.dev/reference/react/use-client) at the top of a file, above your imports.

`"use client` is used to declare a boundary between a Server and Client Component module graph. This means
that by defining a `"use client"` in a file, all other modules imported into it, including child components, are considered part of the client bundle - and will be rendered by React on the client.

```tsx filename="app/counter.tsx" highlight={1} switcher
'use client'

import { useState } from 'react'

export default function Counter() {
const [count, setCount] = useState(0)

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
```

```jsx filename="app/counter.js" highlight={1} switcher
'use client'

import { useState } from 'react'

export default function Counter() {
const [count, setCount] = useState(0)

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
)
}
```

<Image
alt="Use Client Directive and Network Boundary"
srcLight="/docs/light/use-client-directive.png"
srcDark="/docs/dark/use-client-directive.png"
width="1600"
height="1320"
/>

> **Multiple `use client` boundaries**:
>
> You can define multile "use client" boundaries in your React Component tree. This allows you to split your application into multiple bundles (or branches), and only render the components that are needed for a route at runtime.
>
> However, `"use client"` doesn't need to be defined in every component that needs to be rendered on the client. Once you define the boundary, all components and modules imported into it, or in other words, the branch in the tree is considered part of the client bundle.

## How are Client Components Rendered?

How Client Components are rendered depends on whether the user is visiting your application for the first time or if it's a subsequent navigation.

### Initial Visit

To optimize the initial page load, Next.js will use React's APIs to render a static HTML preview on the server for both Client and Server Components. This means, when the user first visits your application, they will see the content of the page immediately, without having to wait for the client to download and parse the Client Component JavaScript bundle.

On the client, React does three things:

1. Reconciles the Client and Server Component trees.
2. Updates the DOM.
3. Use the Client Components JavaScript bundle to hydrate Client Components - this makes the UI interactive.

{/* Diagram */}

> **What is hydration?**

> Hydration is process of attaching event listeners to the DOM, to make the static HTML interactive. In React, hydration is done with the [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot) API.

### Subsequent Navigations

On subsequent navigations, Client Components are rendered entirely on the client, without the server-rendered HTML preview.

## Switching back to the Server Environment

Sometimes, after you've declared the ``"use client"` directive, you may want to switch back to the server environment. For example, you may want to reduce the client bundle size, fetch data on the server, or use an API that is only available on the server.

In cases like this, you can interleave Client and Server Components in the same branch, see the [Composition Patterns](/docs/app/building-your-application/rendering#composition-patterns) documentation for implementation details.

This file was deleted.

Loading