0

What is the reason for isTrue not changing to true? As you can see I am setting it inside the useEffect. What exactly is happening here?

import React, {useState, useEffect} from "react";
import "./style.css";

export default function App() {
  const [isTrue, setIsTrue] = useState(false)

  useEffect(() => {
    setIsTrue(true)
    console.log(isTrue) //still gives me false
  }, [])

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
yilkur
  • 31
  • 4
  • 1
    Does this answer your question? [React setState not Updating Immediately](https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately) – Ivar Mar 05 '21 at 10:40

1 Answers1

0

You have a closure on isTrue === false value, you can have another useEffect which listens to its changes:

export default function App() {
  const [isTrue, setIsTrue] = useState(false);

  useEffect(() => {
    setIsTrue(true);
  }, []);

  useEffect(() => {
    console.log(isTrue);
  }, [isTrue]);

  return (
    <div>
      <h1>Hello StackBlitz!</h1>
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118