Trying to update the state in the first render causes React to go into an infinite loop
Direct update:
function App() {
const [state, setState] = useState(false);
setState(false);
return <div>hello</div>;
}
Result:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
But it works fine when the update is run after a timeout
After timeout:
function App() {
const [state, setState] = useState(false);
setTimeout(() => {
setState(false);
}, 1000);
return <div>hello</div>;
}
Results:
hello
I know it's not good practice. The question is more about how it works than how to make it work.
Is the first render of useState
somehow different?