diff --git a/src/content/learn/passing-data-deeply-with-context.md b/src/content/learn/passing-data-deeply-with-context.md index fead4056db..9165b5eea0 100644 --- a/src/content/learn/passing-data-deeply-with-context.md +++ b/src/content/learn/passing-data-deeply-with-context.md @@ -1,36 +1,36 @@ --- -title: Passing Data Deeply with Context +title: Passando dados profundamente com contexto --- -Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. *Context* lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props. +Normalmente, você passará informações de um componente pai para um componente filho por meio de props. Mas passar props pode se tornar verboso e inconveniente se você precisar passá-las por muitos componentes intermediários, ou se muitos componentes da sua aplicação precisarem da mesma informação. *Contexto* permite que o componente pai disponibilize algumas informações para qualquer componente na árvore abaixo dele—não importa quão profundo—sem passá-las explicitamente por props. -- What "prop drilling" is -- How to replace repetitive prop passing with context -- Common use cases for context -- Common alternatives to context +- O que é "prop drilling" +- Como substituir a passagem repetitiva de props por contexto +- Casos de uso comuns para contexto +- Alternativas comuns ao contexto -## The problem with passing props {/*the-problem-with-passing-props*/} +## O problema de passar props {/*the-problem-with-passing-props*/} -[Passing props](/learn/passing-props-to-a-component) is a great way to explicitly pipe data through your UI tree to the components that use it. +[Passar props](/learn/passing-props-to-a-component) é uma ótima maneira de canalizar dados explicitamente pela sua árvore de UI até os componentes que os utilizam. -But passing props can become verbose and inconvenient when you need to pass some prop deeply through the tree, or if many components need the same prop. The nearest common ancestor could be far removed from the components that need data, and [lifting state up](/learn/sharing-state-between-components) that high can lead to a situation called "prop drilling". +Mas passar props pode se tornar verboso e inconveniente quando você precisa passar alguma prop profundamente pela árvore, ou se muitos componentes precisam da mesma prop. O ancestral comum mais próximo pode estar muito distante dos componentes que precisam dos dados, e [elevar o estado](/learn/sharing-state-between-components) até tão alto pode levar a uma situação chamada "prop drilling". - + -Lifting state up +Elevando o estado - + Prop drilling @@ -38,11 +38,11 @@ Prop drilling -Wouldn't it be great if there were a way to "teleport" data to the components in the tree that need it without passing props? With React's context feature, there is! +Não seria ótimo se houvesse uma maneira de "teletransportar" dados para os componentes da árvore que precisam deles sem passar props? Com o recurso de contexto do React, existe! -## Context: an alternative to passing props {/*context-an-alternative-to-passing-props*/} +## Contexto: uma alternativa a passar props {/*context-an-alternative-to-passing-props*/} -Context lets a parent component provide data to the entire tree below it. There are many uses for context. Here is one example. Consider this `Heading` component that accepts a `level` for its size: +O contexto permite que um componente pai forneça dados para toda a árvore abaixo dele. Há muitos usos para o contexto. Aqui está um exemplo. Considere este componente `Heading` que aceita um `level` para o seu tamanho: @@ -106,7 +106,7 @@ export default function Heading({ level, children }) { -Let's say you want multiple headings within the same `Section` to always have the same size: +Digamos que você queira que vários títulos dentro da mesma `Section` sempre tenham o mesmo tamanho: @@ -180,7 +180,7 @@ export default function Heading({ level, children }) { -Currently, you pass the `level` prop to each `` separately: +Atualmente, você passa a prop `level` para cada `` separadamente: ```js
@@ -190,7 +190,7 @@ Currently, you pass the `level` prop to each `` separately:
``` -It would be nice if you could pass the `level` prop to the `
` component instead and remove it from the ``. This way you could enforce that all headings in the same section have the same size: +Seria bom se, em vez disso, você pudesse passar a prop `level` para o componente `
` e removê-la do ``. Dessa forma, você poderia garantir que todos os títulos na mesma seção tenham o mesmo tamanho: ```js
@@ -200,35 +200,35 @@ It would be nice if you could pass the `level` prop to the `
` component
``` -But how can the `` component know the level of its closest `
`? **That would require some way for a child to "ask" for data from somewhere above in the tree.** +Mas como o componente `` pode saber o nível da `
` mais próxima? **Isso exigiria alguma forma de um filho "pedir" dados de algum lugar acima na árvore.** -You can't do it with props alone. This is where context comes into play. You will do it in three steps: +Você não consegue fazer isso apenas com props. É aqui que o contexto entra em cena. Você fará isso em três etapas: -1. **Create** a context. (You can call it `LevelContext`, since it's for the heading level.) -2. **Use** that context from the component that needs the data. (`Heading` will use `LevelContext`.) -3. **Provide** that context from the component that specifies the data. (`Section` will provide `LevelContext`.) +1. **Crie** um contexto. (Você pode chamá-lo de `LevelContext`, já que ele é para o nível do título.) +2. **Use** esse contexto no componente que precisa dos dados. (`Heading` usará `LevelContext`.) +3. **Forneça** esse contexto a partir do componente que especifica os dados. (`Section` fornecerá `LevelContext`.) -Context lets a parent--even a distant one!--provide some data to the entire tree inside of it. +O contexto permite que um pai--mesmo um distante!--forneça alguns dados para toda a árvore dentro dele. - + -Using context in close children +Usando contexto em filhos próximos - + -Using context in distant children +Usando contexto em filhos distantes -### Step 1: Create the context {/*step-1-create-the-context*/} +### Etapa 1: Crie o contexto {/*step-1-create-the-context*/} -First, you need to create the context. You'll need to **export it from a file** so that your components can use it: +Primeiro, você precisa criar o contexto. Você precisará **exportá-lo de um arquivo** para que seus componentes possam usá-lo: @@ -308,18 +308,18 @@ export const LevelContext = createContext(1); -The only argument to `createContext` is the _default_ value. Here, `1` refers to the biggest heading level, but you could pass any kind of value (even an object). You will see the significance of the default value in the next step. +O único argumento de `createContext` é o valor _padrão_. Aqui, `1` se refere ao maior nível de título, mas você poderia passar qualquer tipo de valor (até mesmo um objeto). Você verá a importância do valor padrão na próxima etapa. -### Step 2: Use the context {/*step-2-use-the-context*/} +### Etapa 2: Use o contexto {/*step-2-use-the-context*/} -Import the `useContext` Hook from React and your context: +Importe o Hook `useContext` do React e o seu contexto: ```js import { useContext } from 'react'; import { LevelContext } from './LevelContext.js'; ``` -Currently, the `Heading` component reads `level` from props: +Atualmente, o componente `Heading` lê `level` das props: ```js export default function Heading({ level, children }) { @@ -327,7 +327,7 @@ export default function Heading({ level, children }) { } ``` -Instead, remove the `level` prop and read the value from the context you just imported, `LevelContext`: +Em vez disso, remova a prop `level` e leia o valor do contexto que você acabou de importar, `LevelContext`: ```js {2} export default function Heading({ children }) { @@ -336,9 +336,9 @@ export default function Heading({ children }) { } ``` -`useContext` is a Hook. Just like `useState` and `useReducer`, you can only call a Hook immediately inside a React component (not inside loops or conditions). **`useContext` tells React that the `Heading` component wants to read the `LevelContext`.** +`useContext` é um Hook. Assim como `useState` e `useReducer`, você só pode chamar um Hook imediatamente dentro de um componente React (não dentro de loops ou condições). **`useContext` diz ao React que o componente `Heading` quer ler o `LevelContext`.** -Now that the `Heading` component doesn't have a `level` prop, you don't need to pass the level prop to `Heading` in your JSX like this anymore: +Agora que o componente `Heading` não tem uma prop `level`, você não precisa mais passar a prop level para `Heading` no seu JSX desta forma: ```js
@@ -348,7 +348,7 @@ Now that the `Heading` component doesn't have a `level` prop, you don't need to
``` -Update the JSX so that it's the `Section` that receives it instead: +Atualize o JSX para que, em vez disso, seja a `Section` que a receba: ```jsx
@@ -358,7 +358,7 @@ Update the JSX so that it's the `Section` that receives it instead:
``` -As a reminder, this is the markup that you were trying to get working: +Como lembrete, esta é a marcação que você estava tentando fazer funcionar: @@ -442,13 +442,13 @@ export const LevelContext = createContext(1); -Notice this example doesn't quite work, yet! All the headings have the same size because **even though you're *using* the context, you have not *provided* it yet.** React doesn't know where to get it! +Observe que este exemplo ainda não funciona totalmente! Todos os títulos têm o mesmo tamanho porque **mesmo que você esteja *usando* o contexto, você ainda não o *forneceu*.** O React não sabe de onde obtê-lo! -If you don't provide the context, React will use the default value you've specified in the previous step. In this example, you specified `1` as the argument to `createContext`, so `useContext(LevelContext)` returns `1`, setting all those headings to `

`. Let's fix this problem by having each `Section` provide its own context. +Se você não fornecer o contexto, o React usará o valor padrão que você especificou na etapa anterior. Neste exemplo, você especificou `1` como argumento para `createContext`, então `useContext(LevelContext)` retorna `1`, definindo todos esses títulos como `

`. Vamos corrigir esse problema fazendo com que cada `Section` forneça seu próprio contexto. -### Step 3: Provide the context {/*step-3-provide-the-context*/} +### Etapa 3: Forneça o contexto {/*step-3-provide-the-context*/} -The `Section` component currently renders its children: +O componente `Section` atualmente renderiza seus filhos: ```js export default function Section({ children }) { @@ -460,7 +460,7 @@ export default function Section({ children }) { } ``` -**Wrap them with a context provider** to provide the `LevelContext` to them: +**Envolva-os com um provedor de contexto** para fornecer o `LevelContext` a eles: ```js {1,6,8} import { LevelContext } from './LevelContext.js'; @@ -476,7 +476,7 @@ export default function Section({ level, children }) { } ``` -This tells React: "if any component inside this `
` asks for `LevelContext`, give them this `level`." The component will use the value of the nearest `` in the UI tree above it. +Isso diz ao React: "se algum componente dentro desta `
` pedir `LevelContext`, dê a ele este `level`." O componente usará o valor do `` mais próximo na árvore de UI acima dele. @@ -564,15 +564,15 @@ export const LevelContext = createContext(1); -It's the same result as the original code, but you did not need to pass the `level` prop to each `Heading` component! Instead, it "figures out" its heading level by asking the closest `Section` above: +É o mesmo resultado do código original, mas você não precisou passar a prop `level` para cada componente `Heading`! Em vez disso, ele "descobre" o nível do seu título perguntando à `Section` mais próxima acima: -1. You pass a `level` prop to the `
`. -2. `Section` wraps its children into ``. -3. `Heading` asks the closest value of `LevelContext` above with `useContext(LevelContext)`. +1. Você passa uma prop `level` para a `
`. +2. `Section` envolve seus filhos em ``. +3. `Heading` pede o valor mais próximo de `LevelContext` acima com `useContext(LevelContext)`. -## Using and providing context from the same component {/*using-and-providing-context-from-the-same-component*/} +## Usando e fornecendo contexto no mesmo componente {/*using-and-providing-context-from-the-same-component*/} -Currently, you still have to specify each section's `level` manually: +Atualmente, você ainda precisa especificar o `level` de cada seção manualmente: ```js export default function Page() { @@ -585,7 +585,7 @@ export default function Page() { ... ``` -Since context lets you read information from a component above, each `Section` could read the `level` from the `Section` above, and pass `level + 1` down automatically. Here is how you could do it: +Como o contexto permite que você leia informações de um componente acima, cada `Section` poderia ler o `level` da `Section` acima e passar `level + 1` para baixo automaticamente. Veja como você poderia fazer isso: ```js src/Section.js {5,8} import { useContext } from 'react'; @@ -603,7 +603,7 @@ export default function Section({ children }) { } ``` -With this change, you don't need to pass the `level` prop *either* to the `
` or to the ``: +Com essa mudança, você não precisa passar a prop `level` *nem* para a `
` nem para o ``: @@ -695,19 +695,19 @@ export const LevelContext = createContext(0); -Now both `Heading` and `Section` read the `LevelContext` to figure out how "deep" they are. And the `Section` wraps its children into the `LevelContext` to specify that anything inside of it is at a "deeper" level. +Agora, tanto `Heading` quanto `Section` leem o `LevelContext` para descobrir quão "profundos" eles estão. E a `Section` envolve seus filhos no `LevelContext` para especificar que qualquer coisa dentro dela está em um nível "mais profundo". -This example uses heading levels because they show visually how nested components can override context. But context is useful for many other use cases too. You can pass down any information needed by the entire subtree: the current color theme, the currently logged in user, and so on. +Este exemplo usa níveis de título porque eles mostram visualmente como componentes aninhados podem sobrescrever o contexto. Mas o contexto também é útil para muitos outros casos de uso. Você pode passar para baixo qualquer informação necessária para toda a subárvore: o tema de cores atual, o usuário logado no momento e assim por diante. -## Context passes through intermediate components {/*context-passes-through-intermediate-components*/} +## O contexto passa por componentes intermediários {/*context-passes-through-intermediate-components*/} -You can insert as many components as you like between the component that provides context and the one that uses it. This includes both built-in components like `
` and components you might build yourself. +Você pode inserir quantos componentes quiser entre o componente que fornece o contexto e aquele que o usa. Isso inclui tanto componentes nativos como `
` quanto componentes que você mesmo pode criar. -In this example, the same `Post` component (with a dashed border) is rendered at two different nesting levels. Notice that the `` inside of it gets its level automatically from the closest `
`: +Neste exemplo, o mesmo componente `Post` (com uma borda tracejada) é renderizado em dois níveis de aninhamento diferentes. Observe que o `` dentro dele obtém seu nível automaticamente da `
` mais próxima: @@ -832,58 +832,58 @@ export const LevelContext = createContext(0); -You didn't do anything special for this to work. A `Section` specifies the context for the tree inside it, so you can insert a `` anywhere, and it will have the correct size. Try it in the sandbox above! +Você não fez nada de especial para isso funcionar. Uma `Section` especifica o contexto para a árvore dentro dela, então você pode inserir um `` em qualquer lugar, e ele terá o tamanho correto. Experimente no sandbox acima! -**Context lets you write components that "adapt to their surroundings" and display themselves differently depending on _where_ (or, in other words, _in which context_) they are being rendered.** +**O contexto permite que você escreva componentes que "se adaptam ao ambiente ao seu redor" e se exibem de forma diferente dependendo de _onde_ (ou, em outras palavras, _em qual contexto_) estão sendo renderizados.** -How context works might remind you of [CSS property inheritance.](https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance) In CSS, you can specify `color: blue` for a `
`, and any DOM node inside of it, no matter how deep, will inherit that color unless some other DOM node in the middle overrides it with `color: green`. Similarly, in React, the only way to override some context coming from above is to wrap children into a context provider with a different value. +O funcionamento do contexto pode lembrar você da [herança de propriedades CSS.](https://developer.mozilla.org/pt-BR/docs/Web/CSS/inheritance) No CSS, você pode especificar `color: blue` para uma `
`, e qualquer nó do DOM dentro dela, não importa quão profundo, herdará essa cor, a menos que algum outro nó do DOM no meio a sobrescreva com `color: green`. Da mesma forma, no React, a única maneira de sobrescrever algum contexto vindo de cima é envolver os filhos em um provedor de contexto com um valor diferente. -In CSS, different properties like `color` and `background-color` don't override each other. You can set all `
`'s `color` to red without impacting `background-color`. Similarly, **different React contexts don't override each other.** Each context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* context. One component may use or provide many different contexts without a problem. +No CSS, propriedades diferentes como `color` e `background-color` não sobrescrevem umas às outras. Você pode definir a `color` de todas as `
` como vermelha sem afetar a `background-color`. Da mesma forma, **contextos diferentes do React não sobrescrevem uns aos outros.** Cada contexto que você cria com `createContext()` é completamente separado dos outros e une os componentes que usam e fornecem *especificamente aquele* contexto. Um componente pode usar ou fornecer muitos contextos diferentes sem problemas. -## Before you use context {/*before-you-use-context*/} +## Antes de usar contexto {/*before-you-use-context*/} -Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into context.** +O contexto é muito tentador de usar! No entanto, isso também significa que é fácil demais usá-lo em excesso. **Só porque você precisa passar algumas props vários níveis abaixo não significa que você deva colocar essa informação no contexto.** -Here's a few alternatives you should consider before using context: +Aqui estão algumas alternativas que você deve considerar antes de usar o contexto: -1. **Start by [passing props.](/learn/passing-props-to-a-component)** If your components are not trivial, it's not unusual to pass a dozen props down through a dozen components. It may feel like a slog, but it makes it very clear which components use which data! The person maintaining your code will be glad you've made the data flow explicit with props. -2. **Extract components and [pass JSX as `children`](/learn/passing-props-to-a-component#passing-jsx-as-children) to them.** If you pass some data through many layers of intermediate components that don't use that data (and only pass it further down), this often means that you forgot to extract some components along the way. For example, maybe you pass data props like `posts` to visual components that don't use them directly, like ``. Instead, make `Layout` take `children` as a prop, and render ``. This reduces the number of layers between the component specifying the data and the one that needs it. +1. **Comece [passando props.](/learn/passing-props-to-a-component)** Se seus componentes não forem triviais, não é incomum passar uma dúzia de props por uma dúzia de componentes. Pode parecer um trabalho maçante, mas isso deixa muito claro quais componentes usam quais dados! A pessoa que mantém seu código ficará feliz por você ter tornado o fluxo de dados explícito com props. +2. **Extraia componentes e [passe JSX como `children`](/learn/passing-props-to-a-component#passing-jsx-as-children) para eles.** Se você passa alguns dados por muitas camadas de componentes intermediários que não usam esses dados (e apenas os repassam adiante), isso muitas vezes significa que você se esqueceu de extrair alguns componentes pelo caminho. Por exemplo, talvez você passe props de dados como `posts` para componentes visuais que não as usam diretamente, como ``. Em vez disso, faça `Layout` receber `children` como prop e renderize ``. Isso reduz o número de camadas entre o componente que especifica os dados e aquele que precisa deles. -If neither of these approaches works well for you, consider context. +Se nenhuma dessas abordagens funcionar bem para você, considere o contexto. -## Use cases for context {/*use-cases-for-context*/} +## Casos de uso para contexto {/*use-cases-for-context*/} -* **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look. -* **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value. -* **Routing:** Most routing solutions use context internally to hold the current route. This is how every link "knows" whether it's active or not. If you build your own router, you might want to do it too. -* **Managing state:** As your app grows, you might end up with a lot of state closer to the top of your app. Many distant components below may want to change it. It is common to [use a reducer together with context](/learn/scaling-up-with-reducer-and-context) to manage complex state and pass it down to distant components without too much hassle. +* **Temas:** Se sua aplicação permite que o usuário mude a aparência dela (por exemplo, modo escuro), você pode colocar um provedor de contexto no topo da sua aplicação e usar esse contexto nos componentes que precisam ajustar sua aparência visual. +* **Conta atual:** Muitos componentes podem precisar saber qual é o usuário logado no momento. Colocá-lo no contexto torna conveniente lê-lo em qualquer lugar da árvore. Algumas aplicações também permitem que você opere várias contas ao mesmo tempo (por exemplo, para deixar um comentário como outro usuário). Nesses casos, pode ser conveniente envolver uma parte da UI em um provedor aninhado com um valor diferente de conta atual. +* **Roteamento:** A maioria das soluções de roteamento usa contexto internamente para guardar a rota atual. É assim que cada link "sabe" se está ativo ou não. Se você construir seu próprio roteador, talvez queira fazer isso também. +* **Gerenciamento de estado:** À medida que sua aplicação cresce, você pode acabar com muito estado mais perto do topo da sua aplicação. Muitos componentes distantes abaixo podem querer alterá-lo. É comum [usar um reducer junto com o contexto](/learn/scaling-up-with-reducer-and-context) para gerenciar estado complexo e passá-lo para componentes distantes sem muita complicação. -Context is not limited to static values. If you pass a different value on the next render, React will update all the components reading it below! This is why context is often used in combination with state. +O contexto não se limita a valores estáticos. Se você passar um valor diferente na próxima renderização, o React atualizará todos os componentes abaixo que o leem! É por isso que o contexto é frequentemente usado em combinação com o estado. -In general, if some information is needed by distant components in different parts of the tree, it's a good indication that context will help you. +Em geral, se alguma informação é necessária para componentes distantes em diferentes partes da árvore, é um bom indício de que o contexto vai ajudar você. -* Context lets a component provide some information to the entire tree below it. -* To pass context: - 1. Create and export it with `export const MyContext = createContext(defaultValue)`. - 2. Pass it to the `useContext(MyContext)` Hook to read it in any child component, no matter how deep. - 3. Wrap children into `` to provide it from a parent. -* Context passes through any components in the middle. -* Context lets you write components that "adapt to their surroundings". -* Before you use context, try passing props or passing JSX as `children`. +* O contexto permite que um componente forneça algumas informações para toda a árvore abaixo dele. +* Para passar contexto: + 1. Crie-o e exporte-o com `export const MyContext = createContext(defaultValue)`. + 2. Passe-o para o Hook `useContext(MyContext)` para lê-lo em qualquer componente filho, não importa quão profundo. + 3. Envolva os filhos em `` para fornecê-lo a partir de um pai. +* O contexto passa por quaisquer componentes intermediários. +* O contexto permite que você escreva componentes que "se adaptam ao ambiente ao seu redor". +* Antes de usar contexto, tente passar props ou passar JSX como `children`. -#### Replace prop drilling with context {/*replace-prop-drilling-with-context*/} +#### Substitua prop drilling por contexto {/*replace-prop-drilling-with-context*/} -In this example, toggling the checkbox changes the `imageSize` prop passed to each ``. The checkbox state is held in the top-level `App` component, but each `` needs to be aware of it. +Neste exemplo, marcar ou desmarcar a caixa de seleção muda a prop `imageSize` passada para cada ``. O estado da caixa de seleção é mantido no componente `App` de nível superior, mas cada `` precisa estar ciente dele. -Currently, `App` passes `imageSize` to `List`, which passes it to each `Place`, which passes it to the `PlaceImage`. Remove the `imageSize` prop, and instead pass it from the `App` component directly to `PlaceImage`. +Atualmente, `App` passa `imageSize` para `List`, que a passa para cada `Place`, que a passa para `PlaceImage`. Remova a prop `imageSize` e, em vez disso, passe-a diretamente do componente `App` para `PlaceImage`. -You can declare context in `Context.js`. +Você pode declarar o contexto em `Context.js`. @@ -1020,9 +1020,9 @@ li { -Remove `imageSize` prop from all the components. +Remova a prop `imageSize` de todos os componentes. -Create and export `ImageSizeContext` from `Context.js`. Then wrap the List into `` to pass the value down, and `useContext(ImageSizeContext)` to read it in the `PlaceImage`: +Crie e exporte `ImageSizeContext` a partir de `Context.js`. Em seguida, envolva a List em `` para passar o valor para baixo, e use `useContext(ImageSizeContext)` para lê-lo em `PlaceImage`: @@ -1157,7 +1157,7 @@ li { -Note how components in the middle don't need to pass `imageSize` anymore. +Observe como os componentes intermediários não precisam mais passar `imageSize`.