Skip to content

Commit 08b194c

Browse files
docs: translate rules-of-hooks.md to Português (Brasil) (#1220)
Co-authored-by: translate-react-bot[bot] <251169733+translate-react-bot[bot]@users.noreply.github.com>
1 parent 9a631dc commit 08b194c

1 file changed

Lines changed: 50 additions & 50 deletions

File tree

src/content/reference/eslint-plugin-react-hooks/lints/rules-of-hooks.md

Lines changed: 50 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -4,89 +4,89 @@ title: rules-of-hooks
44

55
<Intro>
66

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).
88

99
</Intro>
1010

11-
## Rule Details {/*rule-details*/}
11+
## Detalhes da Regra {/*rule-details*/}
1212

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".
1414

15-
## Common Violations {/*common-violations*/}
15+
## Violações Comuns {/*common-violations*/}
1616

17-
These patterns violate the Rules of Hooks:
17+
Estes padrões violam as Regras dos Hooks:
1818

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**
2626

2727
<Note>
2828

29-
### `use` hook {/*use-hook*/}
29+
### Hook `use` {/*use-hook*/}
3030

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:
3232

3333
```js
34-
// ✅ `use` can be conditional
34+
// ✅ `use` pode ser condicional
3535
if (shouldFetch) {
3636
const data = use(fetchPromise);
3737
}
3838

39-
// ✅ `use` can be in loops
39+
// ✅ `use` pode estar em loops
4040
for (const promise of promises) {
4141
results.push(use(promise));
4242
}
4343
```
4444

45-
However, `use` still has restrictions:
46-
- Can't be wrapped in try/catch
47-
- Must be called inside a component or hook
45+
No entanto, `use` ainda tem restrições:
46+
- Não pode ser envolvido em try/catch
47+
- Deve ser chamado dentro de um componente ou hook
4848

49-
Learn more: [`use` API Reference](/reference/react/use)
49+
Saiba mais: [Referência da API `use`](/reference/react/use)
5050

5151
</Note>
5252

53-
### Invalid {/*invalid*/}
53+
### Inválido {/*invalid*/}
5454

55-
Examples of incorrect code for this rule:
55+
Exemplos de código incorreto para esta regra:
5656

5757
```js
58-
// ❌ Hook in condition
58+
// ❌ Hook em condição
5959
if (isLoggedIn) {
6060
const [user, setUser] = useState(null);
6161
}
6262

63-
// ❌ Hook after early return
63+
// ❌ Hook após retorno antecipado
6464
if (!data) return <Loading />;
6565
const [processed, setProcessed] = useState(data);
6666

67-
// ❌ Hook in callback
67+
// ❌ Hook em callback
6868
<button onClick={() => {
6969
const [clicked, setClicked] = useState(false);
7070
}}/>
7171

72-
// ❌ `use` in try/catch
72+
// ❌ `use` em try/catch
7373
try {
7474
const data = use(promise);
7575
} catch (e) {
76-
// error handling
76+
// tratamento de erro
7777
}
7878

79-
// ❌ Hook at module level
80-
const globalState = useState(0); // Outside component
79+
// ❌ Hook no nível do módulo
80+
const globalState = useState(0); // Fora do componente
8181
```
8282

83-
### Valid {/*valid*/}
83+
### Válido {/*valid*/}
8484

85-
Examples of correct code for this rule:
85+
Exemplos de código correto para esta regra:
8686

8787
```js
8888
function Component({ isSpecial, shouldFetch, fetchPromise }) {
89-
// ✅ Hooks at top level
89+
// ✅ Hooks no nível superior
9090
const [count, setCount] = useState(0);
9191
const [name, setName] = useState('');
9292

@@ -95,7 +95,7 @@ function Component({ isSpecial, shouldFetch, fetchPromise }) {
9595
}
9696

9797
if (shouldFetch) {
98-
// ✅ `use` can be conditional
98+
// ✅ `use` pode ser condicional
9999
const data = use(fetchPromise);
100100
return <div>{data}</div>;
101101
}
@@ -104,25 +104,25 @@ function Component({ isSpecial, shouldFetch, fetchPromise }) {
104104
}
105105
```
106106

107-
## Troubleshooting {/*troubleshooting*/}
107+
## Solução de Problemas {/*troubleshooting*/}
108108

109-
### 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*/}
110110

111-
You're trying to conditionally call useEffect:
111+
Você está tentando chamar `useEffect` condicionalmente:
112112

113113
```js
114-
//Conditional hook
114+
//Hook condicional
115115
if (isLoggedIn) {
116116
useEffect(() => {
117117
fetchUserData();
118118
}, []);
119119
}
120120
```
121121

122-
Call the hook unconditionally, check condition inside:
122+
Chame o hook incondicionalmente, verifique a condição dentro dele:
123123

124124
```js
125-
//Condition inside hook
125+
//Condição dentro do hook
126126
useEffect(() => {
127127
if (isLoggedIn) {
128128
fetchUserData();
@@ -132,37 +132,37 @@ useEffect(() => {
132132

133133
<Note>
134134

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.
136136

137-
Learn more: [Fetching Data](/learn/synchronizing-with-effects#fetching-data)
137+
Saiba mais: [Buscando Dados](/learn/synchronizing-with-effects#fetching-data)
138138

139139
</Note>
140140

141-
### I need different state for different scenarios {/*conditional-state-initialization*/}
141+
### Preciso de estados diferentes para cenários diferentes {/*conditional-state-initialization*/}
142142

143-
You're trying to conditionally initialize state:
143+
Você está tentando inicializar o estado condicionalmente:
144144

145145
```js
146-
//Conditional state
146+
//Estado condicional
147147
if (userType === 'admin') {
148148
const [permissions, setPermissions] = useState(adminPerms);
149149
} else {
150150
const [permissions, setPermissions] = useState(userPerms);
151151
}
152152
```
153153

154-
Always call useState, conditionally set the initial value:
154+
Sempre chame `useState`, defina o valor inicial condicionalmente:
155155

156156
```js
157-
//Conditional initial value
157+
//Valor inicial condicional
158158
const [permissions, setPermissions] = useState(
159159
userType === 'admin' ? adminPerms : userPerms
160160
);
161161
```
162162

163-
## Options {/*options*/}
163+
## Opções {/*options*/}
164164

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):
166166

167167
```js
168168
{
@@ -174,6 +174,6 @@ You can configure custom effect hooks using shared ESLint settings (available in
174174
}
175175
```
176176

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.
178178

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

Comments
 (0)