Summary
|
### 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. |
Page
https://react.dev/reference/eslint-plugin-react-hooks/lints/set-state-in-render
Details
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:
// ❌ 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.
I think this Counter component can be rendered and clicked without issues.
The claim that an infinite loop will be triggered is incorrect.
Summary
react.dev/src/content/reference/eslint-plugin-react-hooks/lints/set-state-in-render.md
Lines 70 to 91 in abe931a
Page
https://react.dev/reference/eslint-plugin-react-hooks/lints/set-state-in-render
Details
I think this Counter component can be rendered and clicked without issues.
The claim that an infinite loop will be triggered is incorrect.