AlterionA
Reactiflux4y ago
2 replies
Alterion

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>
  );
}

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?
Was this page helpful?