0
How this code works ?
I know that the useEffect runs whenever the application is rendered for the first time and everytime the state changes. But in this case I cant figure out how the state is updated . Here the setCount function is not called anywhere outside of the useEffect . Then how the count is getting updated ?? import { useState, useEffect } from "react"; import ReactDOM from "react-dom/client"; function Timer() { const [count, setCount] = useState(0); useEffect(() => { setTimeout(() => { setCount((count) => count + 1); }, 1000); }); return <h1>I have rendered {count} times!</h1>; } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Timer />);
1 Respuesta
0
It doesn't matter if the setCount is called inside useEffect, the state will still be updated.
The page renders for the first time. useEffect is called which waits a second to update the state