diff --git a/src/content/reference/eslint-plugin-react-hooks/lints/purity.md b/src/content/reference/eslint-plugin-react-hooks/lints/purity.md index 74c1327597a..c8bdc187c91 100644 --- a/src/content/reference/eslint-plugin-react-hooks/lints/purity.md +++ b/src/content/reference/eslint-plugin-react-hooks/lints/purity.md @@ -60,6 +60,41 @@ function Component() { ## Troubleshooting {/*troubleshooting*/} +### I need to show random content {/*random-content*/} + +Calling `Math.random()` during render makes your component impure: + +```js {expectedErrors: {'react-compiler': [7]}} +const messages = ['a', 'b', 'c']; + +// ❌ Wrong: Random message changes every render +function RandomMessage() { + return ( +
+ Random message: {messages[Math.floor(messages.length * Math.random())]} +
+ ); +} +``` + +Instead, move the impure function into an effect: + +```js +const messages = ['a', 'b', 'c']; + +function RandomMessage() { + const [message, setMessage] = useState(''); + + useEffect(() => { + setMessage(messages[Math.floor(messages.length * Math.random())]); + }, []); + + if (message === '') return; + + return
Random message: {message}
; +} +``` + ### I need to show the current time {/*current-time*/} Calling `Date.now()` during render makes your component impure: @@ -75,7 +110,7 @@ Instead, [move the impure function outside of render](/reference/rules/component ```js function Clock() { - const [time, setTime] = useState(() => Date.now()); + const [time, setTime] = useState(0); useEffect(() => { const interval = setInterval(() => { @@ -85,6 +120,8 @@ function Clock() { return () => clearInterval(interval); }, []); + if (time === 0) return; + return
Current time: {time}
; } -``` \ No newline at end of file +```