const Card: React.FC<{name: string}> = ({ name }) => {
const [x, setX] = React.useState(0)
setX(9)
return <div className="card">
Hello {name} {x}
</div>
}
This code lead to Too many re-renders.
error.
Do this.
const Card: React.FC<{name: string}> = ({ name }) => {
const [x, setX] = React.useState(0)
React.useEffect(() => {
setX(9)
})
return <div className="card">
Hello {name} {x}
</div>
}
At first it looks obvious first code is lead to infinite update loop but why second one does not become infinite? useEffect set callback to be called after render. In this example, callback set state x and this update component. Updating component render the component and call callback again. This time setX set x to 9 and this is same as current state value so update stop. This is different from calling setX at top level and using useEffect. It seems useEffect check equality of state wisely.