Skip to content

Commit 9fcf726

Browse files
authored
Fix "Purity" hydration error, add random content example
1 parent c60922f commit 9fcf726

File tree

1 file changed

+39
-2
lines changed
  • src/content/reference/eslint-plugin-react-hooks/lints

1 file changed

+39
-2
lines changed

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

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,41 @@ function Component() {
6262

6363
## Troubleshooting {/*troubleshooting*/}
6464

65+
### I need to show random content {/*random-content*/}
66+
67+
Calling `Math.random()` during render makes your component impure:
68+
69+
```js {expectedErrors: {'react-compiler': [7]}}
70+
const messages = ['a', 'b', 'c'];
71+
72+
// ❌ Wrong: Random message changes every render
73+
function RandomMessage() {
74+
return (
75+
<div>
76+
Random message: {messages[Math.floor(messages.length * Math.random())]}
77+
</div>
78+
);
79+
}
80+
```
81+
82+
Instead, move the impure function into an effect:
83+
84+
```js
85+
const messages = ['a', 'b', 'c'];
86+
87+
function RandomMessage() {
88+
const [message, setMessage] = useState('');
89+
90+
useEffect(() => {
91+
setMessage(messages[Math.floor(messages.length * Math.random())]);
92+
}, []);
93+
94+
if (message === '') return;
95+
96+
return <div>Random message: {message}</div>;
97+
}
98+
```
99+
65100
### I need to show the current time {/*current-time*/}
66101

67102
Calling `Date.now()` during render makes your component impure:
@@ -77,7 +112,7 @@ Instead, [move the impure function outside of render](/reference/rules/component
77112

78113
```js
79114
function Clock() {
80-
const [time, setTime] = useState(() => Date.now());
115+
const [time, setTime] = useState(0);
81116

82117
useEffect(() => {
83118
const interval = setInterval(() => {
@@ -87,6 +122,8 @@ function Clock() {
87122
return () => clearInterval(interval);
88123
}, []);
89124

125+
if (time === 0) return;
126+
90127
return <div>Current time: {time}</div>;
91128
}
92-
```
129+
```

0 commit comments

Comments
 (0)