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/set-state-in-render.md
+23-23Lines changed: 23 additions & 23 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,37 +4,37 @@ title: set-state-in-render
4
4
5
5
<Intro>
6
6
7
-
Validates against unconditionally setting state during render, which can trigger additional renders and potential infinite render loops.
7
+
Valida contra a definição incondicional de estado durante a renderização, o que pode acionar renderizações adicionais e potenciais loops de renderização infinitos.
8
8
9
9
</Intro>
10
10
11
-
## Rule Details {/*rule-details*/}
11
+
## Detalhes da Regra {/*rule-details*/}
12
12
13
-
Calling`setState`during render unconditionally triggers another render before the current one finishes. This creates an infinite loop that crashes your app.
13
+
Chamar`setState`durante a renderização aciona incondicionalmente outra renderização antes que a atual termine. Isso cria um loop infinito que trava seu aplicativo.
14
14
15
-
## Common Violations {/*common-violations*/}
15
+
## Violações Comuns {/*common-violations*/}
16
16
17
-
### Invalid {/*invalid*/}
17
+
### Inválido {/*invalid*/}
18
18
19
19
```js {expectedErrors: {'react-compiler': [4]}}
20
-
// ❌ Unconditional setState directly in render
20
+
// ❌ setState incondicional diretamente na renderização
21
21
functionComponent({value}) {
22
22
const [count, setCount] =useState(0);
23
-
setCount(value); //Infinite loop!
23
+
setCount(value); //Loop infinito!
24
24
return<div>{count}</div>;
25
25
}
26
26
```
27
27
28
-
### Valid {/*valid*/}
28
+
### Válido {/*valid*/}
29
29
30
30
```js
31
-
// ✅ Derive during render
31
+
// ✅ Derivar durante a renderização
32
32
functionComponent({items}) {
33
-
constsorted= [...items].sort(); //Just calculate it in render
33
+
constsorted= [...items].sort(); //Apenas calcule na renderização
34
34
return<ul>{sorted.map(/*...*/)}</ul>;
35
35
}
36
36
37
-
// ✅ Set state in event handler
37
+
// ✅ Definir estado no manipulador de eventos
38
38
functionComponent() {
39
39
const [count, setCount] =useState(0);
40
40
return (
@@ -44,35 +44,35 @@ function Component() {
44
44
);
45
45
}
46
46
47
-
// ✅ Derive from props instead of setting state
47
+
// ✅ Derivar de props em vez de definir estado
48
48
functionComponent({user}) {
49
49
constname= user?.name||'';
50
50
constemail= user?.email||'';
51
51
return<div>{name}</div>;
52
52
}
53
53
54
-
// ✅ Conditionally derive state from props and state from previous renders
54
+
// ✅ Derivar condicionalmente estado de props e estado de renderizações anteriores
55
55
functionComponent({ items }) {
56
56
const [isReverse, setIsReverse] =useState(false);
57
57
const [selection, setSelection] =useState(null);
58
58
59
59
const [prevItems, setPrevItems] =useState(items);
60
-
if (items !== prevItems) { //This condition makes it valid
60
+
if (items !== prevItems) { //Esta condição a torna válida
61
61
setPrevItems(items);
62
62
setSelection(null);
63
63
}
64
64
// ...
65
65
}
66
66
```
67
67
68
-
## Troubleshooting {/*troubleshooting*/}
68
+
## Solução de Problemas {/*troubleshooting*/}
69
69
70
-
### I want to sync state to a prop {/*clamp-state-to-prop*/}
70
+
### Quero sincronizar o estado com uma prop {/*clamp-state-to-prop*/}
71
71
72
-
A common problem is trying to "fix" state after it renders. Suppose you want to keep a counter from exceeding a `max` prop:
72
+
Um problema comum é tentar "corrigir" o estado após a renderização. Suponha que você queira impedir que um contador exceda uma prop `max`:
73
73
74
74
```js
75
-
// ❌ Wrong: clamps during render
75
+
// ❌ Errado: limita durante a renderização
76
76
functionCounter({max}) {
77
77
const [count, setCount] =useState(0);
78
78
@@ -88,12 +88,12 @@ function Counter({max}) {
88
88
}
89
89
```
90
90
91
-
As soon as `count`exceeds`max`, an infinite loop is triggered.
91
+
Assim que `count`exceder`max`, um loop infinito é acionado.
92
92
93
-
Instead, it's often better to move this logic to the event (the place where the state is first set). For example, you can enforce the maximum at the moment you update state:
93
+
Em vez disso, geralmente é melhor mover essa lógica para o evento (o local onde o estado é definido pela primeira vez). Por exemplo, você pode impor o máximo no momento em que atualiza o estado:
94
94
95
95
```js
96
-
// ✅ Clamp when updating
96
+
// ✅ Limita ao atualizar
97
97
functionCounter({max}) {
98
98
const [count, setCount] =useState(0);
99
99
@@ -105,6 +105,6 @@ function Counter({max}) {
105
105
}
106
106
```
107
107
108
-
Now the setter only runs in response to the click, React finishes the render normally, and`count`never crosses`max`.
108
+
Agora, o setter só é executado em resposta ao clique, o React termina a renderização normalmente e`count`nunca ultrapassa`max`.
109
109
110
-
In rare cases, you may need to adjust state based on information from previous renders. For those, follow [this pattern](https://react.dev/reference/react/useState#storing-information-from-previous-renders) of setting state conditionally.
110
+
Em casos raros, você pode precisar ajustar o estado com base em informações de renderizações anteriores. Para esses casos, siga [este padrão](https://react.dev/reference/react/useState#storing-information-from-previous-renders) de definir o estado condicionalmente.
0 commit comments