Skip to content

Commit 43dd170

Browse files
docs: translate useEffectEvent.md to Português (Brasil) (#1242)
Co-authored-by: translate-react-bot[bot] <251169733+translate-react-bot[bot]@users.noreply.github.com>
1 parent 1d57663 commit 43dd170

1 file changed

Lines changed: 65 additions & 65 deletions

File tree

src/content/reference/react/useEffectEvent.md

Lines changed: 65 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: useEffectEvent
44

55
<Intro>
66

7-
`useEffectEvent` is a React Hook that lets you separate events from Effects.
7+
`useEffectEvent` é um Hook do React que permite separar eventos de Efeitos.
88

99
```js
1010
const onEvent = useEffectEvent(callback)
@@ -16,11 +16,11 @@ const onEvent = useEffectEvent(callback)
1616

1717
---
1818

19-
## Reference {/*reference*/}
19+
## Referência {/*reference*/}
2020

2121
### `useEffectEvent(callback)` {/*useeffectevent*/}
2222

23-
Call `useEffectEvent` at the top level of your component to create an Effect Event.
23+
Chame `useEffectEvent` no nível superior do seu componente para criar um Evento de Efeito.
2424

2525
```js {4,6}
2626
import { useEffectEvent, useEffect } from 'react';
@@ -32,56 +32,56 @@ function ChatRoom({ roomId, theme }) {
3232
}
3333
```
3434

35-
Effect Events are a part of your Effect logic, but they behave more like an event handler. They always “see” the latest values from render (like props and state) without re-synchronizing your Effect, so they're excluded from Effect dependencies. See [Separating Events from Effects](/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects) to learn more.
35+
Eventos de Efeito são parte da lógica do seu Efeito, mas se comportam mais como um manipulador de eventos. Eles sempre "enxergam" os valores mais recentes da renderização (como props e estado) sem re-sincronizar seu Efeito, portanto, são excluídos das dependências do Efeito. Veja [Separando Eventos de Efeitos](/learn/separating-events-from-effects#extracting-non-reactive-logic-out-of-effects) para saber mais.
3636

37-
[See more examples below.](#usage)
37+
[Veja mais exemplos abaixo.](#usage)
3838

39-
#### Parameters {/*parameters*/}
39+
#### Parâmetros {/*parameters*/}
4040

41-
* `callback`: A function containing the logic for your Effect Event. The function can accept any number of arguments and return any value. When you call the returned Effect Event function, the `callback` always accesses the latest committed values from render at the time of the call.
41+
* `callback`: Uma função que contém a lógica para o seu Evento de Efeito. A função pode aceitar qualquer número de argumentos e retornar qualquer valor. Ao chamar a função de Evento de Efeito retornada, o `callback` sempre acessa os valores commitados mais recentes da renderização no momento da chamada.
4242

43-
#### Returns {/*returns*/}
43+
#### Retorna {/*returns*/}
4444

45-
`useEffectEvent` returns an Effect Event function with the same type signature as your `callback`.
45+
`useEffectEvent` retorna uma função de Evento de Efeito com a mesma assinatura de tipo que seu `callback`.
4646

47-
You can call this function inside `useEffect`, `useLayoutEffect`, `useInsertionEffect`, or from within other Effect Events in the same component.
47+
Você pode chamar esta função dentro de `useEffect`, `useLayoutEffect`, `useInsertionEffect`, ou de outros Eventos de Efeito no mesmo componente.
4848

49-
#### Caveats {/*caveats*/}
49+
#### Ressalvas {/*caveats*/}
5050

51-
* `useEffectEvent` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the Effect Event into it.
52-
* Effect Events can only be called from inside Effects or other Effect Events. Do not call them during rendering or pass them to other components or Hooks. The [`eslint-plugin-react-hooks`](/reference/eslint-plugin-react-hooks) linter enforces this restriction.
53-
* Do not use `useEffectEvent` to avoid specifying dependencies in your Effect's dependency array. This hides bugs and makes your code harder to understand. Only use it for logic that is genuinely an event fired from Effects.
54-
* Effect Event functions do not have a stable identity. Their identity intentionally changes on every render.
51+
* `useEffectEvent` é um Hook, então você só pode chamá-lo **no nível superior do seu componente** ou dos seus próprios Hooks. Você não pode chamá-lo dentro de loops ou condições. Se precisar disso, extraia um novo componente e mova o Evento de Efeito para ele.
52+
* Eventos de Efeito só podem ser chamados de dentro de Efeitos ou outros Eventos de Efeito. Não os chame durante a renderização nem os passe para outros componentes ou Hooks. O linter [`eslint-plugin-react-hooks`](/reference/eslint-plugin-react-hooks) impõe essa restrição.
53+
* Não use `useEffectEvent` para evitar especificar dependências no array de dependências do seu Efeito. Isso oculta erros e torna seu código mais difícil de entender. Use-o apenas para lógica que seja genuinamente um evento disparado por Efeitos.
54+
* Funções de Evento de Efeito não possuem uma identidade estável. Sua identidade muda intencionalmente a cada renderização.
5555

5656
<DeepDive>
5757

58-
#### Why are Effect Events not stable? {/*why-are-effect-events-not-stable*/}
58+
#### Por que os Eventos de Efeito não são estáveis? {/*why-are-effect-events-not-stable*/}
5959

60-
Unlike `set` functions from `useState` or refs, Effect Event functions do not have a stable identity. Their identity intentionally changes on every render:
60+
Diferente das funções `set` de `useState` ou de refs, as funções de Evento de Efeito não possuem uma identidade estável. Sua identidade muda intencionalmente a cada renderização:
6161

6262
```js
63-
// 🔴 Wrong: including Effect Event in dependencies
63+
// 🔴 Errado: incluindo Evento de Efeito nas dependências
6464
useEffect(() => {
6565
onSomething();
66-
}, [onSomething]); // ESLint will warn about this
66+
}, [onSomething]); // O ESLint avisará sobre isso
6767
```
6868

69-
This is a deliberate design choice. Effect Events are meant to be called only from within Effects in the same component. Since you can only call them locally and cannot pass them to other components or include them in dependency arrays, a stable identity would serve no purpose, and would actually mask bugs.
69+
Esta é uma escolha de design deliberada. Eventos de Efeito são feitos para serem chamados apenas de dentro de Efeitos no mesmo componente. Como você só pode chamá-los localmente e não pode passá-los para outros componentes ou incluí-los em arrays de dependência, uma identidade estável não teria propósito e, na verdade, mascararia erros.
7070

71-
The non-stable identity acts as a runtime assertion: if your code incorrectly depends on the function identity, you'll see the Effect re-running on every render, making the bug obvious.
71+
A identidade não estável atua como uma asserção em tempo de execução: se seu código depender incorretamente da identidade da função, você verá o Efeito sendo reexecutado a cada renderização, tornando o erro óbvio.
7272

73-
This design reinforces that Effect Events conceptually belong to a particular effect, and are not a general purpose API to opt-out of reactivity.
73+
Este design reforça que os Eventos de Efeito conceitualmente pertencem a um Efeito específico e não são uma API de propósito geral para optar por não reagir.
7474

7575
</DeepDive>
7676

7777
---
7878

79-
## Usage {/*usage*/}
79+
## Uso {/*usage*/}
8080

8181

82-
### Using an event in an Effect {/*using-an-event-in-an-effect*/}
82+
### Usando um evento em um Efeito {/*using-an-event-in-an-effect*/}
8383

84-
Call `useEffectEvent` at the top level of your component to create an *Effect Event*:
84+
Chame `useEffectEvent` no nível superior do seu componente para criar um *Evento de Efeito*:
8585

8686

8787
```js [[1, 1, "onConnected"]]
@@ -92,7 +92,7 @@ const onConnected = useEffectEvent(() => {
9292
});
9393
```
9494

95-
`useEffectEvent` accepts an `event callback` and returns an <CodeStep step={1}>Effect Event</CodeStep>. The Effect Event is a function that can be called inside of Effects without re-connecting the Effect:
95+
`useEffectEvent` aceita um `callback de evento` e retorna um <CodeStep step={1}>Evento de Efeito</CodeStep>. O Evento de Efeito é uma função que pode ser chamada dentro de Efeitos sem re-conectar o Efeito:
9696

9797
```js [[1, 3, "onConnected"]]
9898
useEffect(() => {
@@ -105,38 +105,38 @@ useEffect(() => {
105105
}, [roomId]);
106106
```
107107

108-
Since `onConnected` is an <CodeStep step={1}>Effect Event</CodeStep>, `muted` and `onConnect` are not in the Effect dependencies.
108+
Como `onConnected` é um <CodeStep step={1}>Evento de Efeito</CodeStep>, `muted` e `onConnect` não estão nas dependências do Efeito.
109109

110110
<Pitfall>
111111

112-
##### Don't use Effect Events to skip dependencies {/*pitfall-skip-dependencies*/}
112+
##### Não use Eventos de Efeito para pular dependências {/*pitfall-skip-dependencies*/}
113113

114-
It might be tempting to use `useEffectEvent` to avoid listing dependencies that you think are "unnecessary." However, this hides bugs and makes your code harder to understand:
114+
Pode ser tentador usar `useEffectEvent` para evitar listar dependências que você acha "desnecessárias". No entanto, isso oculta erros e torna seu código mais difícil de entender:
115115

116116
```js
117-
// 🔴 Wrong: Using Effect Events to hide dependencies
117+
// 🔴 Errado: Usando Eventos de Efeito para ocultar dependências
118118
const logVisit = useEffectEvent(() => {
119119
log(pageUrl);
120120
});
121121

122122
useEffect(() => {
123123
logVisit()
124-
}, []); // Missing pageUrl means you miss logs
124+
}, []); // pageUrl ausente significa que você perde logs
125125
```
126126

127-
If a value should cause your Effect to re-run, keep it as a dependency. Only use Effect Events for logic that genuinely should not re-trigger your Effect.
127+
Se um valor deve fazer seu Efeito ser reexecutado, mantenha-o como uma dependência. Use Eventos de Efeito apenas para lógica que genuinamente não deve reativar seu Efeito.
128128

129-
See [Separating Events from Effects](/learn/separating-events-from-effects) to learn more.
129+
Veja [Separando Eventos de Efeitos](/learn/separating-events-from-effects) para saber mais.
130130

131131
</Pitfall>
132132

133133
---
134134

135-
### Using a timer with latest values {/*using-a-timer-with-latest-values*/}
135+
### Usando um timer com valores mais recentes {/*using-a-timer-with-latest-values*/}
136136

137-
When you use `setInterval` or `setTimeout` in an Effect, you often want to read the latest values from render without restarting the timer whenever those values change.
137+
Quando você usa `setInterval` ou `setTimeout` em um Efeito, muitas vezes você quer ler os valores mais recentes da renderização sem reiniciar o timer sempre que esses valores mudam.
138138

139-
This counter increments `count` by the current `increment` value every second. The `onTick` Effect Event reads the latest `count` and `increment` without causing the interval to restart:
139+
Este contador incrementa `count` pelo valor atual de `increment` a cada segundo. O Evento de Efeito `onTick` lê os `count` e `increment` mais recentes sem causar a reinicialização do intervalo:
140140

141141
<Sandpack>
142142

@@ -188,15 +188,15 @@ button { margin: 10px; }
188188

189189
</Sandpack>
190190

191-
Try changing the increment value while the timer is running. The counter immediately uses the new increment value, but the timer keeps ticking smoothly without restarting.
191+
Tente mudar o valor de incremento enquanto o timer está rodando. O contador usa imediatamente o novo valor de incremento, mas o timer continua funcionando suavemente sem reiniciar.
192192

193193
---
194194

195-
### Using an event listener with latest values {/*using-an-event-listener-with-latest-values*/}
195+
### Usando um listener de eventos com valores mais recentes {/*using-an-event-listener-with-latest-values*/}
196196

197-
When you set up an event listener in an Effect, you often need to read the latest values from render in the callback. Without `useEffectEvent`, you would need to include the values in your dependencies, causing the listener to be removed and re-added on every change.
197+
Quando você configura um listener de eventos em um Efeito, muitas vezes precisa ler os valores mais recentes da renderização no callback. Sem `useEffectEvent`, você precisaria incluir os valores em suas dependências, o que faria com que o listener fosse removido e adicionado novamente a cada mudança.
198198

199-
This example shows a dot that follows the cursor, but only when "Can move" is checked. The `onMove` Effect Event always reads the latest `canMove` value without re-running the Effect:
199+
Este exemplo mostra um ponto que segue o cursor, mas apenas quando "Can move" está marcado. O Evento de Efeito `onMove` sempre lê o valor `canMove` mais recente sem reexecutar o Efeito:
200200

201201
<Sandpack>
202202

@@ -254,15 +254,15 @@ body {
254254

255255
</Sandpack>
256256

257-
Toggle the checkbox and move your cursor. The dot responds immediately to the checkbox state, but the event listener is only set up once when the component mounts.
257+
Marque a caixa de seleção e mova o cursor. O ponto responde imediatamente ao estado da caixa de seleção, mas o listener de eventos é configurado apenas uma vez quando o componente é montado.
258258

259259
---
260260

261-
### Avoid reconnecting to external systems {/*showing-a-notification-without-reconnecting*/}
261+
### Evitar reconexões a sistemas externos {/*avoid-reconnecting-to-external-systems*/}
262262

263-
A common use case for `useEffectEvent` is when you want to do something in response to an Effect, but that "something" depends on a value you don't want to react to.
263+
Um caso de uso comum para `useEffectEvent` é quando você quer fazer algo em resposta a um Efeito, mas esse "algo" depende de um valor ao qual você não quer reagir.
264264

265-
In this example, a chat component connects to a room and shows a notification when connected. The user can mute notifications with a checkbox. However, you don't want to reconnect to the chat room every time the user changes the settings:
265+
Neste exemplo, um componente de chat se conecta a uma sala e mostra uma notificação quando conectado. O usuário pode silenciar notificações com uma caixa de seleção. No entanto, você não quer se reconectar à sala de chat toda vez que o usuário muda as configurações:
266266

267267
<Sandpack>
268268

@@ -401,13 +401,13 @@ label { display: block; margin-top: 10px; }
401401

402402
</Sandpack>
403403

404-
Try switching rooms. The chat reconnects and shows a notification. Now mute the notifications. Since `muted` is read inside the Effect Event rather than the Effect, the chat stays connected.
404+
Tente mudar de sala. O chat se reconecta e mostra uma notificação. Agora, silencie as notificações. Como `muted` é lido dentro do Evento de Efeito em vez do Efeito, o chat permanece conectado.
405405

406406
---
407407

408-
### Using Effect Events in custom Hooks {/*using-effect-events-in-custom-hooks*/}
408+
### Usando Eventos de Efeito em Hooks customizados {/*using-effect-events-in-custom-hooks*/}
409409

410-
You can use `useEffectEvent` inside your own custom Hooks. This lets you create reusable Hooks that encapsulate Effects while keeping some values non-reactive:
410+
Você pode usar `useEffectEvent` dentro dos seus próprios Hooks customizados. Isso permite que você crie Hooks reutilizáveis que encapsulam Efeitos, mantendo alguns valores não reativos:
411411

412412
<Sandpack>
413413

@@ -472,26 +472,26 @@ label { display: block; margin-bottom: 8px; }
472472

473473
</Sandpack>
474474

475-
In this example, `useInterval` is a custom Hook that sets up an interval. The `callback` passed to it is wrapped in an Effect Event, so the interval does not reset even if a new `callback` is passed in every render.
475+
Neste exemplo, `useInterval` é um Hook customizado que configura um intervalo. O `callback` passado para ele é envolvido em um Evento de Efeito, então o intervalo não é resetado mesmo que um novo `callback` seja passado a cada renderização.
476476

477477
---
478478

479-
## Troubleshooting {/*troubleshooting*/}
479+
## Solução de problemas {/*troubleshooting*/}
480480

481-
### I'm getting an error: "A function wrapped in useEffectEvent can't be called during rendering" {/*cant-call-during-rendering*/}
481+
### Estou recebendo um erro: "A function wrapped in useEffectEvent can't be called during rendering" {/*cant-call-during-rendering*/}
482482

483-
This error means you're calling an Effect Event function during the render phase of your component. Effect Events can only be called from inside Effects or other Effect Events.
483+
Este erro significa que você está chamando uma função de Evento de Efeito durante a fase de renderização do seu componente. Eventos de Efeito só podem ser chamados de dentro de Efeitos ou outros Eventos de Efeito.
484484

485485
```js
486486
function MyComponent({ data }) {
487487
const onLog = useEffectEvent(() => {
488488
console.log(data);
489489
});
490490

491-
// 🔴 Wrong: calling during render
491+
// 🔴 Errado: chamando durante a renderização
492492
onLog();
493493

494-
//Correct: call from an Effect
494+
//Correto: chamar de um Efeito
495495
useEffect(() => {
496496
onLog();
497497
}, []);
@@ -500,55 +500,55 @@ function MyComponent({ data }) {
500500
}
501501
```
502502

503-
If you need to run logic during render, don't wrap it in `useEffectEvent`. Call the logic directly or move it into an Effect.
503+
Se você precisa executar lógica durante a renderização, não a envolva em `useEffectEvent`. Chame a lógica diretamente ou mova-a para um Efeito.
504504

505505
---
506506

507-
### I'm getting a lint error: "Functions returned from useEffectEvent must not be included in the dependency array" {/*effect-event-in-deps*/}
507+
### Estou recebendo um erro de lint: "Functions returned from useEffectEvent must not be included in the dependency array" {/*effect-event-in-deps*/}
508508

509-
If you see a warning like "Functions returned from `useEffectEvent` must not be included in the dependency array", remove the Effect Event from your dependencies:
509+
Se você vir um aviso como "Functions returned from `useEffectEvent` must not be included in the dependency array", remova o Evento de Efeito de suas dependências:
510510

511511
```js
512512
const onSomething = useEffectEvent(() => {
513513
// ...
514514
});
515515

516-
// 🔴 Wrong: Effect Event in dependencies
516+
// 🔴 Errado: Evento de Efeito nas dependências
517517
useEffect(() => {
518518
onSomething();
519519
}, [onSomething]);
520520

521-
//Correct: no Effect Event in dependencies
521+
//Correto: sem Evento de Efeito nas dependências
522522
useEffect(() => {
523523
onSomething();
524524
}, []);
525525
```
526526

527-
Effect Events are designed to be called from Effects without being listed as dependencies. The linter enforces this because the function identity is [intentionally not stable](#why-are-effect-events-not-stable). Including it would cause your Effect to re-run on every render.
527+
Eventos de Efeito são projetados para serem chamados de Efeitos sem serem listados como dependências. O linter impõe isso porque a identidade da função é [intencionalmente não estável](#why-are-effect-events-not-stable). Incluí-la faria com que seu Efeito fosse reexecutado a cada renderização.
528528

529529
---
530530

531-
### I'm getting a lint error: "... is a function created with useEffectEvent, and can only be called from Effects" {/*effect-event-called-outside-effect*/}
531+
### Estou recebendo um erro de lint: "... is a function created with useEffectEvent, and can only be called from Effects" {/*effect-event-called-outside-effect*/}
532532

533-
If you see a warning like "... is a function created with React Hook `useEffectEvent`, and can only be called from Effects and Effect Events", you're calling the function from the wrong place:
533+
Se você vir um aviso como "... is a function created with React Hook `useEffectEvent`, and can only be called from Effects and Effect Events", você está chamando a função do lugar errado:
534534

535535
```js
536536
const onSomething = useEffectEvent(() => {
537537
console.log(value);
538538
});
539539

540-
// 🔴 Wrong: calling from event handler
540+
// 🔴 Errado: chamando de um manipulador de eventos
541541
function handleClick() {
542542
onSomething();
543543
}
544544

545-
// 🔴 Wrong: passing to child component
545+
// 🔴 Errado: passando para um componente filho
546546
return <Child onSomething={onSomething} />;
547547

548-
//Correct: calling from Effect
548+
//Correto: chamando de um Efeito
549549
useEffect(() => {
550550
onSomething();
551551
}, []);
552552
```
553553

554-
Effect Events are specifically designed to be used in Effects local to the component they're defined in. If you need a callback for event handlers or to pass to children, use a regular function or `useCallback` instead.
554+
Eventos de Efeito são especificamente projetados para serem usados em Efeitos locais ao componente em que são definidos. Se você precisar de um callback para manipuladores de eventos ou para passar para filhos, use uma função regular ou `useCallback` em vez disso.

0 commit comments

Comments
 (0)