From 20a58571591634cf882c716a7b98463590ecf4f1 Mon Sep 17 00:00:00 2001 From: Nivaldo Farias Date: Mon, 10 Feb 2025 23:01:14 -0300 Subject: [PATCH] Translate `use-client.md` to pt-br (#935) Co-authored-by: Jhon Mike --- src/content/reference/rsc/use-client.md | 257 ++++++++++++------------ 1 file changed, 129 insertions(+), 128 deletions(-) diff --git a/src/content/reference/rsc/use-client.md b/src/content/reference/rsc/use-client.md index fe6f5b1ed..0e35bd2eb 100644 --- a/src/content/reference/rsc/use-client.md +++ b/src/content/reference/rsc/use-client.md @@ -5,14 +5,14 @@ titleForTitleTag: "'use client' directive" -`'use client'` is for use with [React Server Components](/learn/start-a-new-react-project#bleeding-edge-react-frameworks). +`'use client'` é para uso com [Componentes do React Server](/learn/start-a-new-react-project#bleeding-edge-react-frameworks). -`'use client'` lets you mark what code runs on the client. +`'use client'` permite que você marque qual código é executado no cliente. @@ -20,11 +20,11 @@ titleForTitleTag: "'use client' directive" --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `'use client'` {/*use-client*/} -Add `'use client'` at the top of a file to mark the module and its transitive dependencies as client code. +Adicione `'use client'` no topo de um arquivo para marcar o módulo e suas dependências transitivas como código do cliente. ```js {1} 'use client'; @@ -41,26 +41,26 @@ export default function RichTextEditor({ timestamp, text }) { } ``` -When a file marked with `'use client'` is imported from a Server Component, [compatible bundlers](/learn/start-a-new-react-project#bleeding-edge-react-frameworks) will treat the module import as a boundary between server-run and client-run code. +Quando um arquivo marcado com `'use client'` é importado de um Componente do Servidor, [empacotadores compatíveis](/learn/start-a-new-react-project#bleeding-edge-react-frameworks) tratarão a importação do módulo como uma fronteira entre código executado no servidor e código executado no cliente. -As dependencies of `RichTextEditor`, `formatDate` and `Button` will also be evaluated on the client regardless of whether their modules contain a `'use client'` directive. Note that a single module may be evaluated on the server when imported from server code and on the client when imported from client code. +Como dependências de `RichTextEditor`, `formatDate` e `Button` também serão avaliados no cliente, independentemente de seus módulos conterem uma diretiva `'use client'`. Note que um único módulo pode ser avaliado no servidor quando importado de código do servidor e no cliente quando importado de código do cliente. -#### Caveats {/*caveats*/} +#### ressalvas {/*caveats*/} -* `'use client'` must be at the very beginning of a file, above any imports or other code (comments are OK). They must be written with single or double quotes, but not backticks. -* When a `'use client'` module is imported from another client-rendered module, the directive has no effect. -* When a component module contains a `'use client'` directive, any usage of that component is guaranteed to be a Client Component. However, a component can still be evaluated on the client even if it does not have a `'use client'` directive. - * A component usage is considered a Client Component if it is defined in module with `'use client'` directive or when it is a transitive dependency of a module that contains a `'use client'` directive. Otherwise, it is a Server Component. -* Code that is marked for client evaluation is not limited to components. All code that is a part of the Client module sub-tree is sent to and run by the client. -* When a server evaluated module imports values from a `'use client'` module, the values must either be a React component or [supported serializable prop values](#passing-props-from-server-to-client-components) to be passed to a Client Component. Any other use case will throw an exception. +* `'use client'` deve estar no início de um arquivo, acima de quaisquer imports ou outros códigos (comentários são permitidos). Devem ser escritos com aspas simples ou duplas, mas não com crases. +* Quando um módulo `'use client'` é importado de outro módulo renderizado pelo cliente, a diretiva não tem efeito. +* Quando um módulo de componente contém uma diretiva `'use client'`, qualquer uso desse componente é garantido como um Componente do Cliente. No entanto, um componente pode ser avaliado ainda no cliente mesmo que não tenha uma diretiva `'use client'`. + * Um uso de componente é considerado um Componente do Cliente se for definido em um módulo com a diretiva `'use client'` ou se for uma dependência transitiva de um módulo que contém uma diretiva `'use client'`. Caso contrário, é um Componente do Servidor. +* O código marcado para avaliação no cliente não se limita a componentes. Todo código que faz parte da subárvore do módulo do Cliente é enviado e executado pelo cliente. +* Quando um módulo avaliado no servidor importa valores de um módulo `'use client'`, os valores devem ser um componente React ou [valores de props serializáveis suportados](#passing-props-from-server-to-client-components) a serem passados para um Componente do Cliente. Qualquer outro caso irá lançar uma exceção. -### How `'use client'` marks client code {/*how-use-client-marks-client-code*/} +### Como o `'use client'` marca código do cliente {/*how-use-client-marks-client-code*/} -In a React app, components are often split into separate files, or [modules](/learn/importing-and-exporting-components#exporting-and-importing-a-component). +Em um aplicativo React, os componentes são frequentemente divididos em arquivos separados, ou [módulos](/learn/importing-and-exporting-components#exporting-and-importing-a-component). -For apps that use React Server Components, the app is server-rendered by default. `'use client'` introduces a server-client boundary in the [module dependency tree](/learn/understanding-your-ui-as-a-tree#the-module-dependency-tree), effectively creating a subtree of Client modules. +Para aplicativos que usam Componentes do Servidor React, o aplicativo é renderizado no servidor por padrão. `'use client'` introduz uma fronteira entre servidor e cliente na [árvore de dependência do módulo](/learn/understanding-your-ui-as-a-tree#the-module-dependency-tree), efetivamente criando uma subárvore de módulos do Cliente. -To better illustrate this, consider the following React Server Components app. +Para ilustrar melhor isso, considere o seguinte aplicativo de Componentes do Servidor React. @@ -104,9 +104,9 @@ export default function InspirationGenerator({children}) { return ( <> -

Your inspirational quote is:

+

Sua citação inspiradora é:

- + {children} ); @@ -121,9 +121,9 @@ export default function Copyright({year}) { ```js src/inspirations.js export default [ - "Don’t let yesterday take up too much of today.” — Will Rogers", - "Ambition is putting a ladder against the sky.", - "A joy that's shared is a joy made double.", + "Não deixe que ontem ocupe muito do hoje.” — Will Rogers", + "Ambição é colocar uma escada contra o céu.", + "Uma alegria compartilhada é uma alegria dobrada.", ]; ``` @@ -145,144 +145,145 @@ export default [
-In the module dependency tree of this example app, the `'use client'` directive in `InspirationGenerator.js` marks that module and all of its transitive dependencies as Client modules. The subtree starting at `InspirationGenerator.js` is now marked as Client modules. +Na árvore de dependência do módulo deste aplicativo de exemplo, a diretiva `'use client'` em `InspirationGenerator.js` marca esse módulo e todas as suas dependências transitivas como módulos do Cliente. A subárvore que começa em `InspirationGenerator.js` agora é marcada como módulos do Cliente. - -`'use client'` segments the module dependency tree of the React Server Components app, marking `InspirationGenerator.js` and all of its dependencies as client-rendered. + +`'use client'` segmenta a árvore de dependência do módulo do aplicativo de Componentes do Servidor React, marcando `InspirationGenerator.js` e todas as suas dependências como renderizadas pelo cliente. -During render, the framework will server-render the root component and continue through the [render tree](/learn/understanding-your-ui-as-a-tree#the-render-tree), opting-out of evaluating any code imported from client-marked code. +Durante a renderização, o framework irá renderizar no servidor o componente raiz e continuará pela [árvore de renderização](/learn/understanding-your-ui-as-a-tree#the-render-tree), optando por não avaliar qualquer código importado de código marcado como cliente. -The server-rendered portion of the render tree is then sent to the client. The client, with its client code downloaded, then completes rendering the rest of the tree. +A porção renderizada no servidor da árvore de renderização é então enviada ao cliente. O cliente, com seu código do cliente baixado, então completa a renderização do restante da árvore. - -The render tree for the React Server Components app. `InspirationGenerator` and its child component `FancyText` are components exported from client-marked code and considered Client Components. + +A árvore de renderização para o aplicativo de Componentes do Servidor React. `InspirationGenerator` e seu componente filho `FancyText` são componentes exportados a partir de código marcado como cliente e considerados Componentes do Cliente. -We introduce the following definitions: +Introduzimos as seguintes definições: -* **Client Components** are components in a render tree that are rendered on the client. -* **Server Components** are components in a render tree that are rendered on the server. +* **Componentes do Cliente** são componentes em uma árvore de renderização que são renderizados no cliente. +* **Componentes do Servidor** são componentes em uma árvore de renderização que são renderizados no servidor. -Working through the example app, `App`, `FancyText` and `Copyright` are all server-rendered and considered Server Components. As `InspirationGenerator.js` and its transitive dependencies are marked as client code, the component `InspirationGenerator` and its child component `FancyText` are Client Components. +Trabalhando através do aplicativo de exemplo, `App`, `FancyText` e `Copyright` são todos renderizados no servidor e considerados Componentes do Servidor. Como `InspirationGenerator.js` e suas dependências transitivas estão marcados como código do cliente, o componente `InspirationGenerator` e seu componente filho `FancyText` são Componentes do Cliente. -#### How is `FancyText` both a Server and a Client Component? {/*how-is-fancytext-both-a-server-and-a-client-component*/} +#### Como `FancyText` é tanto um Componente do Servidor quanto um Componente do Cliente? {/*how-is-fancytext-both-a-server-and-a-client-component*/} -By the above definitions, the component `FancyText` is both a Server and Client Component, how can that be? +Pelas definições acima, o componente `FancyText` é tanto um Componente do Servidor quanto um Componente do Cliente, como isso é possível? -First, let's clarify that the term "component" is not very precise. Here are just two ways "component" can be understood: +Primeiro, vamos esclarecer que o termo "componente" não é muito preciso. Aqui estão apenas duas maneiras que "componente" pode ser entendido: -1. A "component" can refer to a **component definition**. In most cases this will be a function. +1. Um "componente" pode se referir a uma **definição de componente**. Na maioria dos casos, isso será uma função. ```js -// This is a definition of a component +// Esta é uma definição de um componente function MyComponent() { - return

My Component

+ return

Meu Componente

} ``` -2. A "component" can also refer to a **component usage** of its definition. +2. Um "componente" também pode se referir a um **uso de componente** de sua definição. ```js import MyComponent from './MyComponent'; function App() { - // This is a usage of a component + // Este é um uso de um componente return ; } ``` -Often, the imprecision is not important when explaining concepts, but in this case it is. +Frequentemente, a imprecisão não é importante ao explicar conceitos, mas neste caso, é. -When we talk about Server or Client Components, we are referring to component usages. +Quando falamos sobre Componentes do Servidor ou do Cliente, estamos nos referindo a usos de componentes. -* If the component is defined in a module with a `'use client'` directive, or the component is imported and called in a Client Component, then the component usage is a Client Component. -* Otherwise, the component usage is a Server Component. +* Se o componente for definido em um módulo com uma diretiva `'use client'`, ou o componente for importado e chamado em um Componente do Cliente, então o uso do componente é um Componente do Cliente. +* Caso contrário, o uso do componente é um Componente do Servidor. +Uma árvore de renderização ilustra usos de componentes. -A render tree illustrates component usages. +Voltando à questão do `FancyText`, vemos que a definição do componente _não_ possui uma diretiva `'use client'` e tem dois usos. -Back to the question of `FancyText`, we see that the component definition does _not_ have a `'use client'` directive and it has two usages. +O uso de `FancyText` como filho de `App` marca esse uso como um Componente do Servidor. Quando `FancyText` é importado e chamado sob `InspirationGenerator`, esse uso de `FancyText` é um Componente do Cliente, já que `InspirationGenerator` contém uma diretiva `'use client'`. -The usage of `FancyText` as a child of `App`, marks that usage as a Server Component. When `FancyText` is imported and called under `InspirationGenerator`, that usage of `FancyText` is a Client Component as `InspirationGenerator` contains a `'use client'` directive. - -This means that the component definition for `FancyText` will both be evaluated on the server and also downloaded by the client to render its Client Component usage. +Isso significa que a definição do componente para `FancyText` será avaliada tanto no servidor quanto também baixada pelo cliente para renderizar seu uso como Componente do Cliente.
-#### Why is `Copyright` a Server Component? {/*why-is-copyright-a-server-component*/} +#### Por que `Copyright` é um Componente do Servidor? {/*why-is-copyright-a-server-component*/} -Because `Copyright` is rendered as a child of the Client Component `InspirationGenerator`, you might be surprised that it is a Server Component. +Porque `Copyright` é renderizado como um filho do Componente do Cliente `InspirationGenerator`, você pode ficar surpreso que ele é um Componente do Servidor. -Recall that `'use client'` defines the boundary between server and client code on the _module dependency tree_, not the render tree. +Lembre-se de que `'use client'` define a fronteira entre código do servidor e do cliente na _árvore de dependência do módulo_, não na árvore de renderização. - -`'use client'` defines the boundary between server and client code on the module dependency tree. + +`'use client'` define a fronteira entre código do servidor e do cliente na árvore de dependência do módulo. -In the module dependency tree, we see that `App.js` imports and calls `Copyright` from the `Copyright.js` module. As `Copyright.js` does not contain a `'use client'` directive, the component usage is rendered on the server. `App` is rendered on the server as it is the root component. +Na árvore de dependência do módulo, vemos que `App.js` importa e chama `Copyright` do módulo `Copyright.js`. Como `Copyright.js` não contém uma diretiva `'use client'`, o uso do componente é renderizado no servidor. `App` é renderizado no servidor, pois é o componente raiz. -Client Components can render Server Components because you can pass JSX as props. In this case, `InspirationGenerator` receives `Copyright` as [children](/learn/passing-props-to-a-component#passing-jsx-as-children). However, the `InspirationGenerator` module never directly imports the `Copyright` module nor calls the component, all of that is done by `App`. In fact, the `Copyright` component is fully executed before `InspirationGenerator` starts rendering. +Componentes do Cliente podem renderizar Componentes do Servidor porque você pode passar JSX como props. Nesse caso, `InspirationGenerator` recebe `Copyright` como [filhos](/learn/passing-props-to-a-component#passing-jsx-as-children). No entanto, o módulo `InspirationGenerator` nunca importa diretamente o módulo `Copyright` nem chama o componente, tudo isso é feito por `App`. Na verdade, o componente `Copyright` é totalmente executado antes que `InspirationGenerator` comece a renderizar. -The takeaway is that a parent-child render relationship between components does not guarantee the same render environment. +A lição é que uma relação de renderização pai-filho entre componentes não garante o mesmo ambiente de renderização. -### When to use `'use client'` {/*when-to-use-use-client*/} - -With `'use client'`, you can determine when components are Client Components. As Server Components are default, here is a brief overview of the advantages and limitations to Server Components to determine when you need to mark something as client rendered. - -For simplicity, we talk about Server Components, but the same principles apply to all code in your app that is server run. - -#### Advantages of Server Components {/*advantages*/} -* Server Components can reduce the amount of code sent and run by the client. Only Client modules are bundled and evaluated by the client. -* Server Components benefit from running on the server. They can access the local filesystem and may experience low latency for data fetches and network requests. - -#### Limitations of Server Components {/*limitations*/} -* Server Components cannot support interaction as event handlers must be registered and triggered by a client. - * For example, event handlers like `onClick` can only be defined in Client Components. -* Server Components cannot use most Hooks. - * When Server Components are rendered, their output is essentially a list of components for the client to render. Server Components do not persist in memory after render and cannot have their own state. - -### Serializable types returned by Server Components {/*serializable-types*/} - -As in any React app, parent components pass data to child components. As they are rendered in different environments, passing data from a Server Component to a Client Component requires extra consideration. - -Prop values passed from a Server Component to Client Component must be serializable. - -Serializable props include: -* Primitives - * [string](https://developer.mozilla.org/en-US/docs/Glossary/String) - * [number](https://developer.mozilla.org/en-US/docs/Glossary/Number) - * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) - * [boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean) - * [undefined](https://developer.mozilla.org/en-US/docs/Glossary/Undefined) - * [null](https://developer.mozilla.org/en-US/docs/Glossary/Null) - * [symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), only symbols registered in the global Symbol registry via [`Symbol.for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) -* Iterables containing serializable values - * [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) - * [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) - * [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) - * [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) - * [TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) and [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) -* [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) -* Plain [objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object): those created with [object initializers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), with serializable properties -* Functions that are [Server Functions](/reference/rsc/server-functions) -* Client or Server Component elements (JSX) -* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) - -Notably, these are not supported: -* [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that are not exported from client-marked modules or marked with [`'use server'`](/reference/rsc/use-server) -* [Classes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript) -* Objects that are instances of any class (other than the built-ins mentioned) or objects with [a null prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) -* Symbols not registered globally, ex. `Symbol('my new symbol')` - - -## Usage {/*usage*/} - -### Building with interactivity and state {/*building-with-interactivity-and-state*/} +### Quando usar `'use client'` {/*when-to-use-use-client*/} + +Com `'use client'`, você pode determinar quando os componentes são Componentes do Cliente. Como os Componentes do Servidor são padrão, aqui está um breve resumo das vantagens e limitações dos Componentes do Servidor para determinar quando você precisa marcar algo como renderizado pelo cliente. + +Para simplicidade, falamos sobre Componentes do Servidor, mas os mesmos princípios se aplicam a todo código no seu aplicativo que é executado no servidor. + +#### Vantagens dos Componentes do Servidor {/*advantages*/} +* Componentes do Servidor podem reduzir a quantidade de código enviado e executado pelo cliente. Somente módulos do Cliente são empacotados e avaliados pelo cliente. +* Componentes do Servidor se beneficiam de serem executados no servidor. Eles podem acessar o sistema de arquivos local e podem experimentar baixa latência para buscas de dados e requisições de rede. + +#### Limitações dos Componentes do Servidor {/*limitations*/} +* Componentes do Servidor não podem suportar interação, pois os manipuladores de eventos devem ser registrados e acionados por um cliente. + * Por exemplo, manipuladores de eventos como `onClick` só podem ser definidos em Componentes do Cliente. +* Componentes do Servidor não podem usar a maioria dos Hooks. + * Quando os Componentes do Servidor são renderizados, sua saída é essencialmente uma lista de componentes para o cliente renderizar. Componentes do Servidor não persistem em memória após a renderização e não podem ter seu próprio estado. + +### Tipos serializáveis retornados por Componentes do Servidor {/*serializable-types*/} + +Como em qualquer aplicativo React, os componentes pai passam dados para os componentes filhos. Como eles são renderizados em ambientes diferentes, passar dados de um Componente do Servidor para um Componente do Cliente requer consideração extra. + +Os valores das props passadas de um Componente do Servidor para um Componente do Cliente devem ser serializáveis. + +Props serializáveis incluem: +* Primitivos + * [string](https://developer.mozilla.org/pt-BR/docs/Glossary/String) + * [number](https://developer.mozilla.org/pt-BR/docs/Glossary/Number) + * [bigint](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/BigInt) + * [boolean](https://developer.mozilla.org/pt-BR/docs/Glossary/Boolean) + * [undefined](https://developer.mozilla.org/pt-BR/docs/Glossary/Undefined) + * [null](https://developer.mozilla.org/pt-BR/docs/Glossary/Null) + * [symbol](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Symbol), apenas símbolos registrados no registro global de símbolos via [`Symbol.for`](https://developer.mozilla.org/ + + + /docs/Web/JavaScript/Reference/Global_Objects/Symbol/for) +* Iteráveis contendo valores serializáveis + * [String](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String) + * [Array](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array) + * [Map](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Map) + * [Set](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Set) + * [TypedArray](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) e [ArrayBuffer](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) +* [Date](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date) +* [Objetos](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object) simples: aqueles criados com [inicializadores de objetos](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Object_initializer), com propriedades serializáveis +* Funções que são [Funções de Servidor](/reference/rsc/server-functions) +* Elementos de Componente de Cliente ou Servidor (JSX) +* [Promises](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise) + +Notavelmente, estes não são suportados: +* [Funções](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function) que não são exportadas de módulos marcados como cliente ou marcados com [`'use server'`](/reference/rsc/use-server) +* [Classes](https://developer.mozilla.org/pt-BR/docs/Learn/JavaScript/Objects/Classes_in_JavaScript) +* Objetos que são instâncias de qualquer classe (exceto as embutidas mencionadas) ou objetos com [um protótipo nulo](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) +* Símbolos não registrados globalmente, ex. `Symbol('meu novo símbolo')` + +## Uso {/*usage*/} + +### Construindo com interatividade e estado {/*building-with-interactivity-and-state*/} @@ -297,7 +298,7 @@ export default function Counter({initialValue = 0}) { const decrement = () => setCountValue(countValue - 1); return ( <> -

Count Value: {countValue}

+

Valor da Contagem: {countValue}

@@ -307,9 +308,9 @@ export default function Counter({initialValue = 0}) {
-As `Counter` requires both the `useState` Hook and event handlers to increment or decrement the value, this component must be a Client Component and will require a `'use client'` directive at the top. +Como `Counter` requer tanto o Hook `useState` quanto manipuladores de eventos para incrementar ou decrementar o valor, este componente deve ser um Componente do Cliente e exigirá uma diretiva `'use client'` no topo. -In contrast, a component that renders UI without interaction will not need to be a Client Component. +Em contraste, um componente que renderiza UI sem interação não precisará ser um Componente do Cliente. ```js import { readFile } from 'node:fs/promises'; @@ -321,9 +322,9 @@ export default async function CounterContainer() { } ``` -For example, `Counter`'s parent component, `CounterContainer`, does not require `'use client'` as it is not interactive and does not use state. In addition, `CounterContainer` must be a Server Component as it reads from the local file system on the server, which is possible only in a Server Component. +Por exemplo, o componente pai de `Counter`, `CounterContainer`, não requer `'use client'` pois não é interativo e não usa estado. Além disso, `CounterContainer` deve ser um Componente do Servidor, pois lê do sistema de arquivos local no servidor, o que é possível apenas em um Componente do Servidor. -There are also components that don't use any server or client-only features and can be agnostic to where they render. In our earlier example, `FancyText` is one such component. +Existem também componentes que não usam recursos exclusivos do servidor ou do cliente e podem ser indiferentes a onde eles renderizam. Em nosso exemplo anterior, `FancyText` é um desses componentes. ```js export default function FancyText({title, text}) { @@ -333,15 +334,15 @@ export default function FancyText({title, text}) { } ``` -In this case, we don't add the `'use client'` directive, resulting in `FancyText`'s _output_ (rather than its source code) to be sent to the browser when referenced from a Server Component. As demonstrated in the earlier Inspirations app example, `FancyText` is used as both a Server or Client Component, depending on where it is imported and used. +Neste caso, não adicionamos a diretiva `'use client'`, resultando no _output_ de `FancyText` (em vez de seu código-fonte) sendo enviado ao navegador quando referenciado a partir de um Componente do Servidor. Como demonstrado no exemplo anterior do aplicativo Inspirações, `FancyText` é usado como um Componente do Servidor ou do Cliente, dependendo de onde é importado e utilizado. -But if `FancyText`'s HTML output was large relative to its source code (including dependencies), it might be more efficient to force it to always be a Client Component. Components that return a long SVG path string are one case where it may be more efficient to force a component to be a Client Component. +Mas se a saída HTML de `FancyText` fosse grande em relação ao seu código-fonte (incluindo dependências), pode ser mais eficiente forçá-lo a ser sempre um Componente do Cliente. Componentes que retornam uma longa string de caminho SVG são um caso em que pode ser mais eficiente forçar um componente a ser um Componente do Cliente. -### Using client APIs {/*using-client-apis*/} +### Usando APIs do cliente {/*using-client-apis*/} -Your React app may use client-specific APIs, such as the browser's APIs for web storage, audio and video manipulation, and device hardware, among [others](https://developer.mozilla.org/en-US/docs/Web/API). +Seu aplicativo React pode usar APIs específicas do cliente, como as APIs do navegador para armazenamento web, manipulação de áudio e vídeo, e hardware de dispositivos, entre [outras](https://developer.mozilla.org/pt-BR/docs/Web/API). -In this example, the component uses [DOM APIs](https://developer.mozilla.org/en-US/docs/Glossary/DOM) to manipulate a [`canvas`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. Since those APIs are only available in the browser, it must be marked as a Client Component. +Neste exemplo, o componente usa [APIs do DOM](https://developer.mozilla.org/pt-BR/docs/Glossary/DOM) para manipular um [`canvas`](https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/canvas) elemento. Como essas APIs estão disponíveis apenas no navegador, ele deve ser marcado como um Componente do Cliente. ```js 'use client'; @@ -362,18 +363,18 @@ export default function Circle() { } ``` -### Using third-party libraries {/*using-third-party-libraries*/} +### Usando bibliotecas de terceiros {/*using-third-party-libraries*/} -Often in a React app, you'll leverage third-party libraries to handle common UI patterns or logic. +Frequentemente, em um aplicativo React, você utilizará bibliotecas de terceiros para lidar com padrões ou lógica comuns de UI. -These libraries may rely on component Hooks or client APIs. Third-party components that use any of the following React APIs must run on the client: +Essas bibliotecas podem depender de Hooks de componentes ou APIs do cliente. Componentes de terceiros que usam qualquer uma das seguintes APIs do React devem ser executados no cliente: * [createContext](/reference/react/createContext) -* [`react`](/reference/react/hooks) and [`react-dom`](/reference/react-dom/hooks) Hooks, excluding [`use`](/reference/react/use) and [`useId`](/reference/react/useId) +* [`react`](/reference/react/hooks) e [`react-dom`](/reference/react-dom/hooks) Hooks, excluindo [`use`](/reference/react/use) e [`useId`](/reference/react/useId) * [forwardRef](/reference/react/forwardRef) * [memo](/reference/react/memo) * [startTransition](/reference/react/startTransition) -* If they use client APIs, ex. DOM insertion or native platform views +* Se utilizarem APIs do cliente, por exemplo, inserção no DOM ou visualizações nativas da plataforma -If these libraries have been updated to be compatible with React Server Components, then they will already include `'use client'` markers of their own, allowing you to use them directly from your Server Components. If a library hasn't been updated, or if a component needs props like event handlers that can only be specified on the client, you may need to add your own Client Component file in between the third-party Client Component and your Server Component where you'd like to use it. +Se essas bibliotecas foram atualizadas para serem compatíveis com os Componentes do Servidor React, então elas já incluirão marcadores `'use client'` de sua própria, permitindo que você as use diretamente em seus Componentes do Servidor. Se uma biblioteca não foi atualizada, ou se um componente precisa de props como manipuladores de eventos que só podem ser especificados no cliente, talvez seja necessário adicionar seu próprio arquivo de Componente do Cliente entre o Componente do Cliente de terceiros e seu Componente do Servidor onde você gostaria de usá-lo. -[TODO]: <> (Troubleshooting - need use-cases) +[TODO]: <> (Solução de problemas - precisam de casos de uso) \ No newline at end of file