diff --git a/src/content/reference/react/useRef.md b/src/content/reference/react/useRef.md index 8ab53aef3..44034dd4b 100644 --- a/src/content/reference/react/useRef.md +++ b/src/content/reference/react/useRef.md @@ -4,7 +4,7 @@ title: useRef -`useRef` is a React Hook that lets you reference a value that's not needed for rendering. +`useRef` é um Hook React que permite que você referencie um valor que não é necessário para renderização. ```js const ref = useRef(initialValue) @@ -16,11 +16,11 @@ const ref = useRef(initialValue) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `useRef(initialValue)` {/*useref*/} -Call `useRef` at the top level of your component to declare a [ref.](/learn/referencing-values-with-refs) +Chame `useRef` no topo do seu componente para declarar uma [ref.](/learn/referencing-values-with-refs) ```js import { useRef } from 'react'; @@ -31,34 +31,34 @@ function MyComponent() { // ... ``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*parameters*/} -* `initialValue`: The value you want the ref object's `current` property to be initially. It can be a value of any type. This argument is ignored after the initial render. +* `initialValue`: O valor que você quer que a propriedade `current` do objeto ref tenha inicialmente. Pode ser um valor de qualquer tipo. Este argumento é ignorado após a renderização inicial. -#### Returns {/*returns*/} +#### Retorna {/*returns*/} -`useRef` returns an object with a single property: +`useRef` retorna um objeto com uma única propriedade: -* `current`: Initially, it's set to the `initialValue` you have passed. You can later set it to something else. If you pass the ref object to React as a `ref` attribute to a JSX node, React will set its `current` property. +* `current`: Inicialmente, é definido para o `initialValue` que você passou. Você pode, mais tarde, definir para outra coisa. Se você passar o objeto ref para o React como um atributo `ref` para um nó JSX, o React definirá sua propriedade `current`. -On the next renders, `useRef` will return the same object. +Nas próximas renderizações, `useRef` retornará o mesmo objeto. -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -* You can mutate the `ref.current` property. Unlike state, it is mutable. However, if it holds an object that is used for rendering (for example, a piece of your state), then you shouldn't mutate that object. -* When you change the `ref.current` property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object. -* Do not write _or read_ `ref.current` during rendering, except for [initialization.](#avoiding-recreating-the-ref-contents) This makes your component's behavior unpredictable. -* In Strict Mode, React will **call your component function twice** in order to [help you find accidental impurities.](/reference/react/useState#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. Each ref object will be created twice, but one of the versions will be discarded. If your component function is pure (as it should be), this should not affect the behavior. +* Você pode mutar a propriedade `ref.current`. Diferente do state, é mutável. No entanto, se ele contiver um objeto que é usado para renderização (por exemplo, uma parte do seu state), então você não deve mutar esse objeto. +* Quando você muda a propriedade `ref.current`, o React não re-renderiza o seu componente. O React não está ciente quando você o muda porque uma ref é um objeto JavaScript simples. +* Não escreva _ou leia_ `ref.current` durante a renderização, exceto para [inicialização.](#avoiding-recreating-the-ref-contents) Isso torna o comportamento do seu componente imprevisível. +* No Strict Mode, o React irá **chamar a função do seu componente duas vezes** para [ajudar você a encontrar impurezas acidentais.](/reference/react/useState#my-initializer-or-updater-function-runs-twice) Esse é um comportamento apenas para desenvolvimento e não afeta a produção. Cada objeto ref será criado duas vezes, mas uma das versões será descartada. Se a função do seu componente é pura (como deveria ser), isso não deve afetar o comportamento. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Referencing a value with a ref {/*referencing-a-value-with-a-ref*/} +### Referenciando um valor com uma ref {/*referencing-a-value-with-a-ref*/} -Call `useRef` at the top level of your component to declare one or more [refs.](/learn/referencing-values-with-refs) +Chame `useRef` no nível mais alto do seu componente para declarar um ou mais [refs.](/learn/referencing-values-with-refs) ```js [[1, 4, "intervalRef"], [3, 4, "0"]] import { useRef } from 'react'; @@ -68,11 +68,11 @@ function Stopwatch() { // ... ``` -`useRef` returns a ref object with a single `current` property initially set to the initial value you provided. +`useRef` retorna um objeto ref com uma única propriedade `current` inicialmente definida para o valor inicial que você forneceu. -On the next renders, `useRef` will return the same object. You can change its `current` property to store information and read it later. This might remind you of [state](/reference/react/useState), but there is an important difference. +Nas renderizações seguintes, `useRef` retornará o mesmo objeto. Você pode mudar sua propriedade `current` para armazenar informações e lê-las depois. Isso pode fazer você lembrar do [state](/reference/react/useState), mas há uma diferença importante. -**Changing a ref does not trigger a re-render.** This means refs are perfect for storing information that doesn't affect the visual output of your component. For example, if you need to store an [interval ID](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) and retrieve it later, you can put it in a ref. To update the value inside the ref, you need to manually change its `current` property: +**Mudar uma ref não dispara uma re-renderização.** Isso significa que as refs são perfeitas para armazenar informações que não afetam a saída visual do seu componente. Por exemplo, se você precisar armazenar um [ID de intervalo](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) e recuperá-lo depois, você pode colocá-lo em uma ref. Para atualizar o valor dentro da ref, você precisa mudar manualmente sua propriedade `current`: ```js [[2, 5, "intervalRef.current"]] function handleStartClick() { @@ -83,7 +83,7 @@ function handleStartClick() { } ``` -Later, you can read that interval ID from the ref so that you can call [clear that interval](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval): +Mais tarde, você pode ler o ID do intervalo da ref para que possa chamar [clear o intervalo](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval): ```js [[2, 2, "intervalRef.current"]] function handleStopClick() { @@ -92,19 +92,19 @@ function handleStopClick() { } ``` -By using a ref, you ensure that: +Ao usar uma ref, você garante que: -- You can **store information** between re-renders (unlike regular variables, which reset on every render). -- Changing it **does not trigger a re-render** (unlike state variables, which trigger a re-render). -- The **information is local** to each copy of your component (unlike the variables outside, which are shared). +- Você pode **armazenar informações** entre as re-renderizações (diferente das variáveis normais, que reiniciam em cada renderização). +- Mudá-la **não dispara uma re-renderização** (diferente das variáveis do state, que disparam uma re-renderização). +- A **informação é local** para cada cópia do seu componente (diferente das variáveis externas, que são compartilhadas). -Changing a ref does not trigger a re-render, so refs are not appropriate for storing information you want to display on the screen. Use state for that instead. Read more about [choosing between `useRef` and `useState`.](/learn/referencing-values-with-refs#differences-between-refs-and-state) +Mudar uma ref não dispara uma re-renderização, então refs não são apropriadas para armazenar informações que você quer exibir na tela. Use state para isso. Leia mais sobre [escolher entre `useRef` e `useState`.](/learn/referencing-values-with-refs#differences-between-refs-and-state) - + -#### Click counter {/*click-counter*/} +#### Contador de cliques {/*click-counter*/} -This component uses a ref to keep track of how many times the button was clicked. Note that it's okay to use a ref instead of state here because the click count is only read and written in an event handler. +Este componente usa uma ref para controlar quantas vezes o botão foi clicado. Note que é aceitável usar uma ref em vez de state aqui porque a contagem de cliques é somente lida e escrita em um manipulador de evento. @@ -129,13 +129,13 @@ export default function Counter() { -If you show `{ref.current}` in the JSX, the number won't update on click. This is because setting `ref.current` does not trigger a re-render. Information that's used for rendering should be state instead. +Se você mostrar `{ref.current}` no JSX, o número não irá atualizar no clique. Isso ocorre porque definir `ref.current` não dispara uma re-renderização. Informações que são usadas para renderização deveriam ser state, em vez disso. -#### A stopwatch {/*a-stopwatch*/} +#### Um cronômetro {/*a-stopwatch*/} -This example uses a combination of state and refs. Both `startTime` and `now` are state variables because they are used for rendering. But we also need to hold an [interval ID](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) so that we can stop the interval on button press. Since the interval ID is not used for rendering, it's appropriate to keep it in a ref, and manually update it. +Este exemplo usa uma combinação de state e refs. Ambos `startTime` e `now` são variáveis de state porque elas são usadas para renderização. Mas nós também precisamos manter um [ID de intervalo](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) para que possamos parar o intervalo na pressão do botão. Já que o ID do intervalo não é usado para renderização, é apropriado mantê-lo em uma ref e atualizá-lo manualmente. @@ -188,57 +188,57 @@ export default function Stopwatch() { -**Do not write _or read_ `ref.current` during rendering.** +**Não escreva _ou leia_ `ref.current` durante a renderização.** -React expects that the body of your component [behaves like a pure function](/learn/keeping-components-pure): +O React espera que o corpo do seu componente [se comporte como uma função pura](/learn/keeping-components-pure): -- If the inputs ([props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), and [context](/learn/passing-data-deeply-with-context)) are the same, it should return exactly the same JSX. -- Calling it in a different order or with different arguments should not affect the results of other calls. +- Se os _inputs_ ([props](/learn/passing-props-to-a-component), [state](/learn/state-a-components-memory), e [contexto](/learn/passing-data-deeply-with-context)) forem os mesmos, ele deverá retornar exatamente o mesmo JSX. +- Chamá-la em uma ordem diferente ou com argumentos diferentes não deverá afetar os resultados de outras chamadas. -Reading or writing a ref **during rendering** breaks these expectations. +Ler ou escrever uma ref **durante a renderização** quebra essas expectativas. ```js {3-4,6-7} function MyComponent() { // ... - // 🚩 Don't write a ref during rendering + // 🚩 Não escreva uma ref durante a renderização myRef.current = 123; // ... - // 🚩 Don't read a ref during rendering + // 🚩 Não leia uma ref durante a renderização return

{myOtherRef.current}

; } ``` -You can read or write refs **from event handlers or effects instead**. +Você pode ler ou escrever refs **de manipuladores de eventos ou effects, em vez disso**. ```js {4-5,9-10} function MyComponent() { // ... useEffect(() => { - // ✅ You can read or write refs in effects + // ✅ Você pode ler ou escrever refs em effects myRef.current = 123; }); // ... function handleClick() { - // ✅ You can read or write refs in event handlers + // ✅ Você pode ler ou escrever refs em manipuladores de eventos doSomething(myOtherRef.current); } // ... } ``` -If you *have to* read [or write](/reference/react/useState#storing-information-from-previous-renders) something during rendering, [use state](/reference/react/useState) instead. +Se você *tiver que* ler [ou escrever](/reference/react/useState#storing-information-from-previous-renders) algo durante a renderização, [use o state](/reference/react/useState) em vez disso. -When you break these rules, your component might still work, but most of the newer features we're adding to React will rely on these expectations. Read more about [keeping your components pure.](/learn/keeping-components-pure#where-you-_can_-cause-side-effects) +Quando você quebra essas regras, seu componente ainda pode funcionar, mas a maioria dos recursos mais novos que estamos adicionando ao React dependerão dessas expectativas. Leia mais sobre [manter seus componentes puros.](/learn/keeping-components-pure#where-you-_can_-cause-side-effects)
--- -### Manipulating the DOM with a ref {/*manipulating-the-dom-with-a-ref*/} +### Manipulando o DOM com uma ref {/*manipulating-the-dom-with-a-ref*/} -It's particularly common to use a ref to manipulate the [DOM.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API) React has built-in support for this. +É particularmente comum usar uma ref para manipular o [DOM.](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API) O React tem suporte embutido para isso. -First, declare a ref object with an initial value of `null`: +Primeiramente, declare um objeto ref com um valor inicial de `null`: ```js [[1, 4, "inputRef"], [3, 4, "null"]] import { useRef } from 'react'; @@ -248,14 +248,14 @@ function MyComponent() { // ... ``` -Then pass your ref object as the `ref` attribute to the JSX of the DOM node you want to manipulate: +Então passe o seu objeto ref como o atributo `ref` para o JSX do nó do DOM que você quer manipular: ```js [[1, 2, "inputRef"]] // ... return ; ``` -After React creates the DOM node and puts it on the screen, React will set the `current` property of your ref object to that DOM node. Now you can access the ``'s DOM node and call methods like [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus): +Depois que o React cria o nó do DOM e o coloca na tela, o React irá definir a propriedade `current` do seu objeto ref para esse nó do DOM. Agora você pode acessar o nó DOM do `` e chamar métodos como [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus): ```js [[2, 2, "inputRef.current"]] function handleClick() { @@ -263,15 +263,15 @@ After React creates the DOM node and puts it on the screen, React will set the < } ``` -React will set the `current` property back to `null` when the node is removed from the screen. +O React irá definir a propriedade `current` de volta para `null` quando o nó for removido da tela. -Read more about [manipulating the DOM with refs.](/learn/manipulating-the-dom-with-refs) +Leia mais sobre [manipular o DOM com refs.](/learn/manipulating-the-dom-with-refs) - + -#### Focusing a text input {/*focusing-a-text-input*/} +#### Focando uma entrada de texto {/*focusing-a-text-input*/} -In this example, clicking the button will focus the input: +Neste exemplo, clicar no botão irá focar no _input_: @@ -300,9 +300,9 @@ export default function Form() { -#### Scrolling an image into view {/*scrolling-an-image-into-view*/} +#### Rolando uma imagem para dentro da visão {/*scrolling-an-image-into-view*/} -In this example, clicking the button will scroll an image into view. It uses a ref to the list DOM node, and then calls DOM [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) API to find the image we want to scroll to. +Neste exemplo, clicar no botão irá rolar uma imagem para dentro da visão. Ele usa uma ref para o nó DOM da lista, e então chama a API DOM [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) para encontrar a imagem que queremos rolar até. @@ -314,7 +314,7 @@ export default function CatFriends() { function scrollToIndex(index) { const listNode = listRef.current; - // This line assumes a particular DOM structure: + // Essa linha assume uma estrutura DOM em particular: const imgNode = listNode.querySelectorAll('li > img')[index]; imgNode.scrollIntoView({ behavior: 'smooth', @@ -393,9 +393,9 @@ li { -#### Playing and pausing a video {/*playing-and-pausing-a-video*/} +#### Reproduzindo e pausando um vídeo {/*playing-and-pausing-a-video*/} -This example uses a ref to call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on a `