Skip to content

docs(pt-br): translate react-apis and createContext page #667

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

Merged
merged 10 commits into from
Apr 27, 2023
14 changes: 7 additions & 7 deletions src/content/reference/react/apis.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
---
title: "Built-in React APIs"
title: "APIs React Integradas"
---

<Intro>

In addition to [Hooks](/reference/react) and [Components](/reference/react/components), the `react` package exports a few other APIs that are useful for defining components. This page lists all the remaining modern React APIs.
Em adição aos [Hooks](/reference/react) e [Componentes](/reference/react/components), o pacote `react` exporta algumas outras APIs que são úteis para definir componentes. Essa página lista todas as APIs modernas restantes do React.

</Intro>

---

* [`createContext`](/reference/react/createContext) lets you define and provide context to the child components. Used with [`useContext`.](/reference/react/useContext)
* [`forwardRef`](/reference/react/forwardRef) lets your component expose a DOM node as a ref to the parent. Used with [`useRef`.](/reference/react/useRef)
* [`lazy`](/reference/react/lazy) lets you defer loading a component's code until it's rendered for the first time.
* [`memo`](/reference/react/memo) lets your component skip re-renders with same props. Used with [`useMemo`](/reference/react/useMemo) and [`useCallback`.](/reference/react/useCallback)
* [`startTransition`](/reference/react/startTransition) lets you mark a state update as non-urgent. Similar to [`useTransition`.](/reference/react/useTransition)
* [`createContext`](/reference/react/createContext) permite que você defina e forneça contexto aos componentes filhos. Utilizado com [`useContext`.](/reference/react/useContext)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

não sei se gosto da tradução literal pra "contexto", porque permite que você defina e forneça contexto aos componentes filhos fica subjetivo, não faz o mesmo sentido.

talvez devemos tentar algo como: permite que você defina e forneça propriedades através de um context aos componentes filhos. Utilizado com [useContext.]

ficaria mais descritivo e traria mais proximidade ao significado inicial, sem perder a proximidade com o português

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oi @lirbre . Essa discussão vai ser bem relevante e acho que terá diversas opiniões: no texto original, não usam Context em maiúsculo, portanto não parecem estar usando como nome próprio e sim como a palavra em seu significado comum. Nesse sentido, faria sentido traduzir...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concordo com o @jotaRenan. Nessa parte eu entendi o uso de "context" com o sentido mais para o lado do contexto de uma conversa

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agora estou considerando melhor a ideia do @lirbre. Talvez realmente seja uma boa adicionar mais informação.

permite que você defina e forneça contexto aos componentes filhos através dos valores de um context.

O que acham?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A fim de manter a tradução mais próxima do texto original, respeitosamente mantenho minha opinião

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eu gostei do jeito que esta 🤔, acho que da para entender!! oq acham podemos seguir?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

compreendo, excelentes pontos! acho que podemos seguir sim.

* [`forwardRef`](/reference/react/forwardRef) permite que seu componente exponha um nó do DOM como uma referência para o pai. Utilizado com [`useRef`.](/reference/react/useRef)
* [`lazy`](/reference/react/lazy) permite adiar o carregamento do código de um componente até que ele seja renderizado pela primeira vez.
* [`memo`](/reference/react/memo) permite que seu componente evite re-renderizações se as propriedades (`props`) forem as mesmas. Utilizado com [`useMemo`](/reference/react/useMemo) e [`useCallback`.](/reference/react/useCallback)
* [`startTransition`](/reference/react/startTransition) permite marcar uma atualização de estado como não urgente. Semelhante a [`useTransition`.](/reference/react/useTransition)
78 changes: 37 additions & 41 deletions src/content/reference/react/createContext.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: createContext

<Intro>

`createContext` lets you create a [context](/learn/passing-data-deeply-with-context) that components can provide or read.
`createContext` permite que você crie um [contexto](/learn/passing-data-deeply-with-context) que componentes podem fornecer ou consumir.

```js
const SomeContext = createContext(defaultValue)
Expand All @@ -16,38 +16,38 @@ const SomeContext = createContext(defaultValue)

---

## Reference {/*reference*/}
## Referência {/*reference*/}

### `createContext(defaultValue)` {/*createcontext*/}

Call `createContext` outside of any components to create a context.
Invoque `createContext` fora de qualquer componente para criar um contexto.

```js
import { createContext } from 'react';

const ThemeContext = createContext('light');
```

[See more examples below.](#usage)
[Veja mais exemplos abaixo.](#usage)

#### Parameters {/*parameters*/}
#### Parâmetros {/*parameters*/}

* `defaultValue`: The value that you want the context to have when there is no matching context provider in the tree above the component that reads context. If you don't have any meaningful default value, specify `null`. The default value is meant as a "last resort" fallback. It is static and never changes over time.
* `defaultValue`: O valor que você quer que o contexto tenha quando não há um provedor de contexto correspondente na árvore acima do componente que lê o contexto. Se você não tem um valor padrão significativo, especifique `null`. O valor padrão é um "último recurso" reserva. Ele é estático e nunca muda com o tempo.

#### Returns {/*returns*/}
#### Retornos {/*returns*/}

`createContext` returns a context object.
`createContext` retorna um objeto de contexto.

**The context object itself does not hold any information.** It represents _which_ context other components read or provide. Typically, you will use [`SomeContext.Provider`](#provider) in components above to specify the context value, and call [`useContext(SomeContext)`](/reference/react/useContext) in components below to read it. The context object has a few properties:
**O objeto de contexto em si, não possui nenhuma informação.** Ele representa _qual_ contexto outros componentes irão consumir ou fornecer. Geralmente, você vai usar[`SomeContext.Provider`](#provider) em um componente acima para especificar um valor para o contexto, e invocar [`useContext(SomeContext)`](/reference/react/useContext) em componentes abaixo pra consumi-lo. O objeto de contexto possui algumas propriedades:

* `SomeContext.Provider` lets you provide the context value to components.
* `SomeContext.Consumer` is an alternative and rarely used way to read the context value.
* `SomeContext.Provider` permite que você forneça o valor do contexto aos seus componentes.
* `SomeContext.Consumer` é uma alternativa raramanete usada como uma forma de consumir o valor de um contexto.

---

### `SomeContext.Provider` {/*provider*/}

Wrap your components into a context provider to specify the value of this context for all components inside:
Envolva seus componente em um provedor de contexto para especificar o valor desse contexto para todos os componentes dentro dele:

```js
function App() {
Expand All @@ -63,17 +63,17 @@ function App() {

#### Props {/*provider-props*/}

* `value`: The value that you want to pass to all the components reading this context inside this provider, no matter how deep. The context value can be of any type. A component calling [`useContext(SomeContext)`](/reference/react/useContext) inside of the provider receives the `value` of the innermost corresponding context provider above it.
* `value`: O valor que você deseja passar para todos os componentes que estão consumindo esse contexto dentro deste provedor, não importa o quão profundo. O valor do contexto pode ser de qualquer tipo. Um componente invocando [`useContext(SomeContext)`](/reference/react/useContext) dentro do provedor recebe o `value` do provedor de contexto correspondente mais próximo acima dele.

---

### `SomeContext.Consumer` {/*consumer*/}

Before `useContext` existed, there was an older way to read context:
Antes do `useContext` existir, havia uma forma mais arcaica de consumir um contexto:

```js
function Button() {
// 🟡 Legacy way (not recommended)
// 🟡 Jeito legado (não recomendado)
return (
<ThemeContext.Consumer>
{theme => (
Expand All @@ -83,30 +83,29 @@ function Button() {
);
}
```

Although this older way still works, but **newly written code should read context with [`useContext()`](/reference/react/useContext) instead:**
Apesar dessa forma mais antiga ainda funcionar, **códigos recém escritos devem consumir o contexto com [`useContext()`](/reference/react/useContext) ao invés disso:**

```js
function Button() {
// ✅ Recommended way
// ✅ Jeito recomendado
const theme = useContext(ThemeContext);
return <button className={theme} />;
}
```

#### Props {/*consumer-props*/}

* `children`: A function. React will call the function you pass with the current context value determined by the same algorithm as [`useContext()`](/reference/react/useContext) does, and render the result you return from this function. React will also re-run this function and update the UI whenever the context from the parent components changes.
* `children`: Uma função. O React invocará a função que você passar com o valor do contexto atual determinado pelo mesmo algoritmo que o [`useContext()`](/reference/react/useContext) utiliza, e renderizará o resultado que você retornar dessa função. O React também irá re-executar essa função e atualizar a UI sempre que o contexto dos componentes pais mudar.

---

## Usage {/*usage*/}
## Uso {/*usage*/}

### Creating context {/*creating-context*/}
### Criando um contexto {/*creating-context*/}

Context lets components [pass information deep down](/learn/passing-data-deeply-with-context) without explicitly passing props.
Contextos permitem [passar informação profundamente](/learn/passing-data-deeply-with-context) sem precisar passar props manualmente em cada nível.

Call `createContext` outside any components to create one or more contexts.
Invoque `createContext` fora de qualquer componente para criar um ou mais contextos.

```js [[1, 3, "ThemeContext"], [1, 4, "AuthContext"], [3, 3, "'light'"], [3, 4, "null"]]
import { createContext } from 'react';
Expand All @@ -115,7 +114,7 @@ const ThemeContext = createContext('light');
const AuthContext = createContext(null);
```

`createContext` returns a <CodeStep step={1}>context object</CodeStep>. Components can read context by passing it to [`useContext()`](/reference/react/useContext):
`createContext` retorna um <CodeStep step={1}>objeto de contexto</CodeStep>. Componentes podem consumir esse contexto passando-o para o hook [`useContext()`](/reference/react/useContext):

```js [[1, 2, "ThemeContext"], [1, 7, "AuthContext"]]
function Button() {
Expand All @@ -129,9 +128,9 @@ function Profile() {
}
```

By default, the values they receive will be the <CodeStep step={3}>default values</CodeStep> you have specified when creating the contexts. However, by itself this isn't useful because the default values never change.
Por padrão, os valores que receberão são os <CodeStep step={3}>valores padrão</CodeStep> que você especificou quando criava os contextos. Porém, por si só isso não é útil porque os valores padrão nunca mudam.

Context is useful because you can **provide other, dynamic values from your components:**
Contextos são úteis porque você pode **fornecer outros valores dinâmicos de seus componentes:**

```js {8-9,11-12}
function App() {
Expand All @@ -150,25 +149,25 @@ function App() {
}
```

Now the `Page` component and any components inside it, no matter how deep, will "see" the passed context values. If the passed context values change, React will re-render the components reading the context as well.
Agora o componente `Page` e qualquer componente dentro dele, não importa o quão profundo esteja, irão "ver" os valores do contexto passados. Se os valores do contexto mudarem, o React também irá re-renderizar os componentes que estão lendo o contexto.

[Read more about reading and providing context and see examples.](/reference/react/useContext)
[Leia mais sobre consumir e providenciar contexto e veja exemplos.](/reference/react/useContext)

---

### Importing and exporting context from a file {/*importing-and-exporting-context-from-a-file*/}
### Importando e exportando contextos de um arquivo {/*importing-and-exporting-context-from-a-file*/}

Often, components in different files will need access to the same context. This is why it's common to declare contexts in a separate file. Then you can use the [`export` statement](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to make context available for other files:
Frequentemente, componentens em arquivos diferentes irão precisar acessar o mesmo contexto. É por isso que é comum declarar contextos em um arquivo separado. Então você pode usar o [`export` statement](https://developer.mozilla.org/pt-BR/docs/web/javascript/reference/statements/export) para tornar o contexto disponível para outros arquivos:

```js {4-5}
// Contexts.js
import { createContext } from 'react';

export const ThemeContext = createContext('light');
export const AuthContext = createContext(null);
````
```

Components declared in other files can then use the [`import`](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import) statement to read or provide this context:
Componentes declarados em outros arquivos podem usar o [`import`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/import) para ler ou providenciar esse contexto:

```js {2}
// Button.js
Expand All @@ -195,23 +194,20 @@ function App() {
);
}
```

This works similar to [importing and exporting components.](/learn/importing-and-exporting-components)
Isso funciona de forma similar com a [importação e exportação de componentes.](/learn/importing-and-exporting-components)

---

## Troubleshooting {/*troubleshooting*/}
## Resolução de problemas {/*troubleshooting*/}

### I can't find a way to change the context value {/*i-cant-find-a-way-to-change-the-context-value*/}
### Não consigo encontrar uma forma de mudar o valor do contexto {/*i-cant-find-a-way-to-change-the-context-value*/}


Code like this specifies the *default* context value:
Código como esse especifica o valor *padrão* do contexto:

```js
const ThemeContext = createContext('light');
```

This value never changes. React only uses this value as a fallback if it can't find a matching provider above.

To make context change over time, [add state and wrap components in a context provider.](/reference/react/useContext#updating-data-passed-via-context)
Esse valor nunca muda. React só usa esse valor como um fallback (reserva) se ele não conseguir encontrar um provedor correspondente acima.

Para fazer o valor do contexto mudar com o tempo, [adicione estado e envolva os componentes em um provedor de contexto (context provider).](/reference/react/useContext#updating-data-passed-via-context)