I am facing some very strange behaviour with useState
React hook. In the following code (https://codesandbox.io/s/purple-bush-nb5uy?file=/src/index.js):
function App() {
return (
<div className="App">
<Comp flag={true} />
</div>
);
}
const Comp = ({ flag }) => {
const [running, setRunning] = useState(false);
const [jumping, setJumping] = useState(false);
console.log('zero');
const setBoth = () => {
setRunning(true);
console.log('one');
setJumping(true);
console.log('two');
};
return (
<>
{"running: " + running}
{"jumping: " + jumping}
<button onClick={() => setBoth()}>setboth</button>
</>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
when we click the button
, we get the following sequence into the console:
one
two
zero
I would expect:
zero
one
zero
two
since I think that React re-renders immediately should it find a useState
setter and the following code executes after re-render. Moreover, that's the case with my React application:
const [time, setTime] = useState('');
console.log('Hey');
const updateTime = (e) => {
setTime(e.details);
console.log('Hello');
};
useEffect(() => {
window.addEventListener("updateTime", updateTime);
return () => {
window.removeEventListener("updateTime", updateTime);
}
}, []);
What happens with the above code when updateTime
runs and when e.details
value is different than state variable time
's content:
Hey
Hello
In other words, the re-rendering runs first and the code after the setter runs afterwards. So, why do we have different behaviour in the above cases? What is the explanation and what happens under the hood?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…