Hindsight – 19-22 May 5

I have a curiosity that I'd like to get a bit of a technical explanation for.
import { useState, useEffect } from "react";

export default function App() {
const [toggle, setToggle] = useState(false);

useEffect(() => {
const timeout = setInterval(() => {
console.log("toggle: ", toggle);
setToggle((oldState) => !oldState);
}, 500);
return () => clearInterval(timeout);
}, []);

return (
<p>{toggle ? "true" : "false"}</p>
);
}
import { useState, useEffect } from "react";

export default function App() {
const [toggle, setToggle] = useState(false);

useEffect(() => {
const timeout = setInterval(() => {
console.log("toggle: ", toggle);
setToggle((oldState) => !oldState);
}, 500);
return () => clearInterval(timeout);
}, []);

return (
<p>{toggle ? "true" : "false"}</p>
);
}
This logs toggle: false systematically, however, it does visually toggle between true and false. I feel this is either related to scopes, closures, or some weird V8 JIT optimisation? Does anyone have a specific explanation for this issue?
2 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
reactibot
reactibot3y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/971854359191253022