You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md
+50-50Lines changed: 50 additions & 50 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,89 +4,89 @@ title: rules-of-hooks
4
4
5
5
<Intro>
6
6
7
-
Validates that components and hooks follow the [Rules of Hooks](/reference/rules/rules-of-hooks).
7
+
Valida se os componentes e hooks seguem as [Regras dos Hooks](/reference/rules/rules-of-hooks).
8
8
9
9
</Intro>
10
10
11
-
## Rule Details {/*rule-details*/}
11
+
## Detalhes da Regra {/*rule-details*/}
12
12
13
-
React relies on the order in which hooks are called to correctly preserve state between renders. Each time your component renders, React expects the exact same hooks to be called in the exact same order. When hooks are called conditionally or in loops, React loses track of which state corresponds to which hook call, leading to bugs like state mismatches and "Rendered fewer/more hooks than expected" errors.
13
+
O React depende da ordem em que os hooks são chamados para preservar corretamente o estado entre as renderizações. Cada vez que seu componente é renderizado, o React espera que os mesmos hooks sejam chamados na mesma ordem. Quando os hooks são chamados condicionalmente ou em loops, o React perde o controle de qual estado corresponde a qual chamada de hook, levando a bugs como inconsistências de estado e erros de "Rendered fewer/more hooks than expected".
14
14
15
-
## Common Violations {/*common-violations*/}
15
+
## Violações Comuns {/*common-violations*/}
16
16
17
-
These patterns violate the Rules of Hooks:
17
+
Estes padrões violam as Regras dos Hooks:
18
18
19
-
-**Hooks in conditions** (`if`/`else`, ternary, `&&`/`||`)
20
-
-**Hooks in loops** (`for`, `while`, `do-while`)
21
-
-**Hooks after early returns**
22
-
-**Hooks in callbacks/event handlers**
23
-
-**Hooks in async functions**
24
-
-**Hooks in class methods**
25
-
-**Hooks at module level**
19
+
-**Hooks em condições** (`if`/`else`, ternário, `&&`/`||`)
20
+
-**Hooks em loops** (`for`, `while`, `do-while`)
21
+
-**Hooks após retornos antecipados**
22
+
-**Hooks em callbacks/manipuladores de eventos**
23
+
-**Hooks em funções assíncronas**
24
+
-**Hooks em métodos de classe**
25
+
-**Hooks no nível do módulo**
26
26
27
27
<Note>
28
28
29
-
### `use` hook {/*use-hook*/}
29
+
### Hook `use` {/*use-hook*/}
30
30
31
-
The `use`hook is different from other React hooks. You can call it conditionally and in loops:
31
+
O hook `use`é diferente de outros hooks do React. Você pode chamá-lo condicionalmente e em loops:
### I want to fetch data based on some condition {/*conditional-data-fetching*/}
109
+
### Quero buscar dados com base em alguma condição {/*conditional-data-fetching*/}
110
110
111
-
You're trying to conditionally call useEffect:
111
+
Você está tentando chamar `useEffect` condicionalmente:
112
112
113
113
```js
114
-
// ❌ Conditional hook
114
+
// ❌ Hook condicional
115
115
if (isLoggedIn) {
116
116
useEffect(() => {
117
117
fetchUserData();
118
118
}, []);
119
119
}
120
120
```
121
121
122
-
Call the hook unconditionally, check condition inside:
122
+
Chame o hook incondicionalmente, verifique a condição dentro dele:
123
123
124
124
```js
125
-
// ✅ Condition inside hook
125
+
// ✅ Condição dentro do hook
126
126
useEffect(() => {
127
127
if (isLoggedIn) {
128
128
fetchUserData();
@@ -132,37 +132,37 @@ useEffect(() => {
132
132
133
133
<Note>
134
134
135
-
There are better ways to fetch data rather than in a useEffect. Consider using TanStack Query, useSWR, or React Router 6.4+ for data fetching. These solutions handle deduplicating requests, caching responses, and avoiding network waterfalls.
135
+
Existem maneiras melhores de buscar dados do que em um `useEffect`. Considere usar TanStack Query, useSWR ou React Router 6.4+ para buscar dados. Essas soluções lidam com a deduplicação de requisições, cache de respostas e evitam "waterfalls" de rede.
Always call useState, conditionally set the initial value:
154
+
Sempre chame `useState`, defina o valor inicial condicionalmente:
155
155
156
156
```js
157
-
// ✅ Conditional initial value
157
+
// ✅ Valor inicial condicional
158
158
const [permissions, setPermissions] =useState(
159
159
userType ==='admin'? adminPerms : userPerms
160
160
);
161
161
```
162
162
163
-
## Options {/*options*/}
163
+
## Opções {/*options*/}
164
164
165
-
You can configure custom effect hooks using shared ESLint settings (available in`eslint-plugin-react-hooks` 6.1.1 and later):
165
+
Você pode configurar hooks de efeito personalizados usando configurações compartilhadas do ESLint (disponíveis no`eslint-plugin-react-hooks` 6.1.1 e posterior):
166
166
167
167
```js
168
168
{
@@ -174,6 +174,6 @@ You can configure custom effect hooks using shared ESLint settings (available in
174
174
}
175
175
```
176
176
177
-
-`additionalEffectHooks`: Regex pattern matching custom hooks that should be treated as effects. This allows `useEffectEvent`and similar event functions to be called from your custom effect hooks.
177
+
-`additionalEffectHooks`: Padrão Regex que corresponde a hooks personalizados que devem ser tratados como efeitos. Isso permite que `useEffectEvent`e funções de evento semelhantes sejam chamados a partir de seus hooks de efeito personalizados.
178
178
179
-
This shared configuration is used by both`rules-of-hooks`and`exhaustive-deps` rules, ensuring consistent behavior across all hook-related linting.
179
+
Esta configuração compartilhada é usada pelas regras`rules-of-hooks`e`exhaustive-deps`, garantindo um comportamento consistente em toda a verificação de linting relacionada a hooks.
0 commit comments