-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Expand file tree
/
Copy pathset-state-in-render.md
More file actions
110 lines (83 loc) · 2.94 KB
/
set-state-in-render.md
File metadata and controls
110 lines (83 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
---
title: set-state-in-render
---
<Intro>
Validates against unconditionally setting state during render, which can trigger additional renders and potential infinite render loops.
</Intro>
## Rule Details {/*rule-details*/}
Calling `setState` during render unconditionally triggers another render before the current one finishes. This creates an infinite loop that crashes your app.
## Common Violations {/*common-violations*/}
### Invalid {/*invalid*/}
```js {expectedErrors: {'react-compiler': [4]}}
// ❌ Unconditional setState directly in render
function Component({value}) {
const [count, setCount] = useState(0);
setCount(value); // Infinite loop!
return <div>{count}</div>;
}
```
### Valid {/*valid*/}
```js
// ✅ Derive during render
function Component({items}) {
const sorted = [...items].sort(); // Just calculate it in render
return <ul>{sorted.map(/*...*/)}</ul>;
}
// ✅ Set state in event handler
function Component() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
// ✅ Derive from props instead of setting state
function Component({user}) {
const name = user?.name || '';
const email = user?.email || '';
return <div>{name}</div>;
}
// ✅ Conditionally derive state from props and state from previous renders
function Component({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) { // This condition makes it valid
setPrevItems(items);
setSelection(null);
}
// ...
}
```
## Troubleshooting {/*troubleshooting*/}
### I want to sync state to a prop {/*clamp-state-to-prop*/}
A common problem is trying to "fix" state after it renders. Suppose you want to keep a counter from exceeding a `max` prop:
```js
// ❌ Wrong: clamps during render
function Counter({max}) {
const [count, setCount] = useState(0);
if (count > max) {
setCount(max);
}
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
);
}
```
As soon as `count` exceeds `max`, an infinite loop is triggered.
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:
```js
// ✅ Clamp when updating
function Counter({max}) {
const [count, setCount] = useState(0);
const increment = () => {
setCount(current => Math.min(current + 1, max));
};
return <button onClick={increment}>{count}</button>;
}
```
Now the setter only runs in response to the click, React finishes the render normally, and `count` never crosses `max`.
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.