Skip to content

Translate server-components.md to pt-br #933

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

Closed
Changes from all commits
Commits
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
127 changes: 63 additions & 64 deletions src/content/reference/rsc/server-components.md
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
---
title: React Server Components
title: Componentes de Servidor do React
canary: true
---

<Intro>

Server Components are a new type of Component that renders ahead of time, before bundling, in an environment separate from your client app or SSR server.
Componentes de Servidor são um novo tipo de Componente que renderiza antecipadamente, antes da empacotamento, em um ambiente separado do seu aplicativo cliente ou servidor SSR.

</Intro>

This separate environment is the "server" in React Server Components. Server Components can run once at build time on your CI server, or they can be run for each request using a web server.
Esse ambiente separado é o "servidor" nos Componentes de Servidor do React. Os Componentes de Servidor podem ser executados uma vez no tempo de construção em seu servidor CI, ou podem ser executados para cada requisição usando um servidor web.

<InlineToc />

<Note>

#### How do I build support for Server Components? {/*how-do-i-build-support-for-server-components*/}
#### Como posso construir suporte para Componentes de Servidor? {/*how-do-i-build-support-for-server-components*/}

While React Server Components in React 19 are stable and will not break between major versions, the underlying APIs used to implement a React Server Components bundler or framework do not follow semver and may break between minors in React 19.x.
Embora os Componentes de Servidor no React 19 sejam estáveis e não quebrem entre versões principais, as APIs subjacentes usadas para implementar um empacotador ou framework de Componentes de Servidor do React não seguem semver e podem quebrar entre menores no React 19.x.

To support React Server Components as a bundler or framework, we recommend pinning to a specific React version, or using the Canary release. We will continue working with bundlers and frameworks to stabilize the APIs used to implement React Server Components in the future.
Para suportar os Componentes de Servidor do React como um empacotador ou framework, recomendamos fixar uma versão específica do React ou usar a versão Canary. Continuaremos trabalhando com empacotadores e frameworks para estabilizar as APIs usadas para implementar Componentes de Servidor do React no futuro.

</Note>

### Server Components without a Server {/*server-components-without-a-server*/}
Server components can run at build time to read from the filesystem or fetch static content, so a web server is not required. For example, you may want to read static data from a content management system.
### Componentes de Servidor sem um Servidor {/*server-components-without-a-server*/}
Os componentes de servidor podem ser executados no tempo de construção para ler do sistema de arquivos ou buscar conteúdo estático, portanto um servidor web não é necessário. Por exemplo, você pode querer ler dados estáticos de um sistema de gerenciamento de conteúdo.

Without Server Components, it's common to fetch static data on the client with an Effect:
Sem os Componentes de Servidor, é comum buscar dados estáticos no cliente com um Effect:
```js
// bundle.js
import marked from 'marked'; // 35.9K (11.2K gzipped)
import sanitizeHtml from 'sanitize-html'; // 206K (63.3K gzipped)

function Page({page}) {
const [content, setContent] = useState('');
// NOTE: loads *after* first page render.
// NOTE: carrega *após* a primeira renderização da página.
useEffect(() => {
fetch(`/api/content/${page}`).then((data) => {
setContent(data.content);
Expand All @@ -53,56 +53,56 @@ app.get(`/api/content/:page`, async (req, res) => {
});
```

This pattern means users need to download and parse an additional 75K (gzipped) of libraries, and wait for a second request to fetch the data after the page loads, just to render static content that will not change for the lifetime of the page.
Esse padrão significa que os usuários precisam baixar e analisar 75K (gzipped) adicionais de bibliotecas e esperar por uma segunda requisição para buscar os dados após a carga da página, apenas para renderizar conteúdo estático que não mudará durante a vida útil da página.

With Server Components, you can render these components once at build time:
Com os Componentes de Servidor, você pode renderizar esses componentes uma vez no tempo de construção:

```js
import marked from 'marked'; // Not included in bundle
import sanitizeHtml from 'sanitize-html'; // Not included in bundle
import marked from 'marked'; // Não incluído no bundle
import sanitizeHtml from 'sanitize-html'; // Não incluído no bundle

async function Page({page}) {
// NOTE: loads *during* render, when the app is built.
// NOTE: carrega *durante* a renderização, quando o aplicativo é construído.
const content = await file.readFile(`${page}.md`);

return <div>{sanitizeHtml(marked(content))}</div>;
}
```

The rendered output can then be server-side rendered (SSR) to HTML and uploaded to a CDN. When the app loads, the client will not see the original `Page` component, or the expensive libraries for rendering the markdown. The client will only see the rendered output:
A saída renderizada pode então ser renderizada no lado do servidor (SSR) para HTML e enviada para um CDN. Quando o aplicativo carrega, o cliente não verá o componente `Page` original, ou as bibliotecas pesadas necessárias para renderizar o markdown. O cliente verá apenas a saída renderizada:

```js
<div><!-- html for markdown --></div>
<div><!-- html para markdown --></div>
```

This means the content is visible during first page load, and the bundle does not include the expensive libraries needed to render the static content.
Isso significa que o conteúdo é visível durante o primeiro carregamento da página, e o bundle não inclui as bibliotecas pesadas necessárias para renderizar o conteúdo estático.

<Note>

You may notice that the Server Component above is an async function:
Você pode notar que o Componente de Servidor acima é uma função assíncrona:

```js
async function Page({page}) {
//...
}
```

Async Components are a new feature of Server Components that allow you to `await` in render.
Componentes Assíncronos são um novo recurso dos Componentes de Servidor que permitem que você `await` na renderização.

See [Async components with Server Components](#async-components-with-server-components) below.
Veja [Componentes assíncronos com Componentes de Servidor](#async-components-with-server-components) abaixo.

</Note>

### Server Components with a Server {/*server-components-with-a-server*/}
Server Components can also run on a web server during a request for a page, letting you access your data layer without having to build an API. They are rendered before your application is bundled, and can pass data and JSX as props to Client Components.
### Componentes de Servidor com um Servidor {/*server-components-with-a-server*/}
Os Componentes de Servidor também podem ser executados em um servidor web durante uma requisição por uma página, permitindo que você acesse sua camada de dados sem ter que construir uma API. Eles são renderizados antes que sua aplicação seja empacotada e podem passar dados e JSX como props para Componentes Cliente.

Without Server Components, it's common to fetch dynamic data on the client in an Effect:
Sem os Componentes de Servidor, é comum buscar dados dinâmicos no cliente em um Effect:

```js
// bundle.js
function Note({id}) {
const [note, setNote] = useState('');
// NOTE: loads *after* first render.
// NOTE: carrega *após* a primeira renderização.
useEffect(() => {
fetch(`/api/notes/${id}`).then(data => {
setNote(data.note);
Expand All @@ -119,15 +119,15 @@ function Note({id}) {

function Author({id}) {
const [author, setAuthor] = useState('');
// NOTE: loads *after* Note renders.
// Causing an expensive client-server waterfall.
// NOTE: carrega *após* a renderização do Note.
// Causando uma cascata pesada entre cliente e servidor.
useEffect(() => {
fetch(`/api/authors/${id}`).then(data => {
setAuthor(data.author);
});
}, [id]);

return <span>By: {author.name}</span>;
return <span>Por: {author.name}</span>;
}
```
```js
Expand All @@ -145,13 +145,13 @@ app.get(`/api/authors/:id`, async (req, res) => {
});
```

With Server Components, you can read the data and render it in the component:
Com os Componentes de Servidor, você pode ler os dados e renderizá-los no componente:

```js
import db from './database';

async function Note({id}) {
// NOTE: loads *during* render.
// NOTE: carrega *durante* a renderização.
const note = await db.notes.get(id);
return (
<div>
Expand All @@ -162,42 +162,41 @@ async function Note({id}) {
}

async function Author({id}) {
// NOTE: loads *after* Note,
// but is fast if data is co-located.
// NOTE: carrega *após* o Note,
// mas é rápido se os dados estiverem co-localizados.
const author = await db.authors.get(id);
return <span>By: {author.name}</span>;
return <span>Por: {author.name}</span>;
}
```

The bundler then combines the data, rendered Server Components and dynamic Client Components into a bundle. Optionally, that bundle can then be server-side rendered (SSR) to create the initial HTML for the page. When the page loads, the browser does not see the original `Note` and `Author` components; only the rendered output is sent to the client:
O empacotador então combina os dados, Componentes de Servidor renderizados e Componentes Cliente dinâmicos em um bundle. Opcionalmente, esse bundle pode ser renderizado no lado do servidor (SSR) para criar o HTML inicial para a página. Quando a página carrega, o navegador não vê os componentes `Note` e `Author` originais; apenas a saída renderizada é enviada ao cliente:

```js
<div>
<span>By: The React Team</span>
<p>React 19 Beta is...</p>
<span>Por: A Equipe do React</span>
<p>O React 19 Beta é...</p>
</div>
```

Server Components can be made dynamic by re-fetching them from a server, where they can access the data and render again. This new application architecture combines the simple “request/response” mental model of server-centric Multi-Page Apps with the seamless interactivity of client-centric Single-Page Apps, giving you the best of both worlds.
Os Componentes de Servidor podem ser tornados dinâmicos ao serem re-buscados de um servidor, onde podem acessar os dados e renderizar novamente. Essa nova arquitetura de aplicação combina o simples modelo mental de "requisição/resposta" de Aplicativos Multiplos de Páginas centrados em servidor com a interatividade contínua de Aplicativos de Página Única centrados em cliente, oferecendo o melhor dos dois mundos.

### Adding interactivity to Server Components {/*adding-interactivity-to-server-components*/}
### Adicionando interatividade aos Componentes de Servidor {/*adding-interactivity-to-server-components*/}

Server Components are not sent to the browser, so they cannot use interactive APIs like `useState`. To add interactivity to Server Components, you can compose them with Client Component using the `"use client"` directive.
Os Componentes de Servidor não são enviados para o navegador, então eles não podem usar APIs interativas como `useState`. Para adicionar interatividade aos Componentes de Servidor, você pode compô-los com um Componente Cliente usando a diretiva `"use client"`.

<Note>

#### There is no directive for Server Components. {/*there-is-no-directive-for-server-components*/}
#### Não há diretiva para Componentes de Servidor. {/*there-is-no-directive-for-server-components*/}

A common misunderstanding is that Server Components are denoted by `"use server"`, but there is no directive for Server Components. The `"use server"` directive is used for Server Actions.
Um mal-entendido comum é que os Componentes de Servidor são denotados por `"use server"`, mas não há diretiva para Componentes de Servidor. A diretiva `"use server"` é usada para Ações do Servidor.

For more info, see the docs for [Directives](/reference/rsc/directives).
Para mais informações, veja os documentos sobre [Diretivas](/reference/rsc/directives).

</Note>


In the following example, the `Notes` Server Component imports an `Expandable` Client Component that uses state to toggle its `expanded` state:
No exemplo seguinte, o Componente de Servidor `Notes` importa um Componente Cliente `Expandable` que usa estado para alternar seu estado `expanded`:
```js
// Server Component
// Componente de Servidor
import Expandable from './Expandable';

async function Notes() {
Expand All @@ -214,7 +213,7 @@ async function Notes() {
}
```
```js
// Client Component
// Componente Cliente
"use client"

export default function Expandable({children}) {
Expand All @@ -224,54 +223,54 @@ export default function Expandable({children}) {
<button
onClick={() => setExpanded(!expanded)}
>
Toggle
Alternar
</button>
{expanded && children}
</div>
)
}
```

This works by first rendering `Notes` as a Server Component, and then instructing the bundler to create a bundle for the Client Component `Expandable`. In the browser, the Client Components will see output of the Server Components passed as props:
Isso funciona renderizando primeiro `Notes` como um Componente de Servidor e, em seguida, instruindo o empacotador a criar um bundle para o Componente Cliente `Expandable`. No navegador, os Componentes Clientes verão a saída dos Componentes de Servidor passados como props:

```js
<head>
<!-- the bundle for Client Components -->
<!-- o bundle para Componentes Clientes -->
<script src="bundle.js" />
</head>
<body>
<div>
<Expandable key={1}>
<p>this is the first note</p>
<p>este é o primeiro note</p>
</Expandable>
<Expandable key={2}>
<p>this is the second note</p>
<p>este é o segundo note</p>
</Expandable>
<!--...-->
</div>
</body>
```

### Async components with Server Components {/*async-components-with-server-components*/}
### Componentes assíncronos com Componentes de Servidor {/*async-components-with-server-components*/}

Server Components introduce a new way to write Components using async/await. When you `await` in an async component, React will suspend and wait for the promise to resolve before resuming rendering. This works across server/client boundaries with streaming support for Suspense.
Os Componentes de Servidor introduzem uma nova maneira de escrever Componentes usando async/await. Quando você `await` em um componente assíncrono, o React suspende e aguarda que a promessa seja resolvida antes de retomar a renderização. Isso funciona por meio de fronteiras entre servidor/cliente com suporte a streaming para Suspense.

You can even create a promise on the server, and await it on the client:
Você pode até criar uma promessa no servidor e aguardá-la no cliente:

```js
// Server Component
// Componente de Servidor
import db from './database';

async function Page({id}) {
// Will suspend the Server Component.
// Suspenderá o Componente de Servidor.
const note = await db.notes.get(id);

// NOTE: not awaited, will start here and await on the client.
// NOTE: não aguardado, começará aqui e aguardará no cliente.
const commentsPromise = db.comments.get(note.id);
return (
<div>
{note}
<Suspense fallback={<p>Loading Comments...</p>}>
<Suspense fallback={<p>Carregando comentários...</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
</div>
Expand All @@ -280,18 +279,18 @@ async function Page({id}) {
```

```js
// Client Component
// Componente Cliente
"use client";
import {use} from 'react';

function Comments({commentsPromise}) {
// NOTE: this will resume the promise from the server.
// It will suspend until the data is available.
// NOTE: isso retomará a promessa do servidor.
// Suspenderá até que os dados estejam disponíveis.
const comments = use(commentsPromise);
return comments.map(commment => <p>{comment}</p>);
return comments.map(comment => <p>{comment}</p>);
}
```

The `note` content is important data for the page to render, so we `await` it on the server. The comments are below the fold and lower-priority, so we start the promise on the server, and wait for it on the client with the `use` API. This will Suspend on the client, without blocking the `note` content from rendering.
O conteúdo do `note` é um dado importante para a renderização da página, então nós `await` ele no servidor. Os comentários estão abaixo da dobra e são de prioridade inferior, então começamos a promessa no servidor e aguardamos no cliente com a API `use`. Isso suspenderá no cliente, sem bloquear o conteúdo `note` de ser renderizado.

Since async components are [not supported on the client](#why-cant-i-use-async-components-on-the-client), we await the promise with `use`.
Uma vez que componentes assíncronos não são [suportados no cliente](#why-cant-i-use-async-components-on-the-client), aguardamos a promessa com `use`.
Loading