0

My useState state is not up to date in useEffect function. It consoles log my old state after I changed it by setState inside useEffect. I know I can use useRef and pass it to useState but it doesn't work inside e.g. setTimeout. Example here (look at hook.js file and console.logs): https://codesandbox.io/s/prod-wildflower-qbwxt

import React, { useEffect, useState } from "react";
import "./styles.css";
import useLoading from "./hook";

function App() {
//  proptype isLoading simulation
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
 setTimeout(() => setIsLoading(true), 3000);
}, []);

// hook
const delayedLoading = useLoading(isLoading);

return (
 <div className="App">
   <h1>Hello {`${delayedLoading}`}</h1>
   <h2>Start editing to see some magic happen!</h2>
 </div>
);
}

export default App;
import React, { useEffect, useState } from "react";
import "./styles.css";
import useLoading from "./hook";

function App() {
  //  proptype isLoading simulation
  const [isLoading, setIsLoading] = useState(false);
  useEffect(() => {
    setTimeout(() => setIsLoading(true), 3000);
  }, []);

  // hook
  const delayedLoading = useLoading(isLoading);

  return (
    <div className="App">
      <h1>Hello {`${delayedLoading}`}</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

export default App;

Marcinek
  • 47
  • 4
  • Please put code in your stackoverflow question, not just in a codesandbox. What's going on is that you are counting on setState being synchronous, however, it is not. Your setLoading hook is going to be initializes with the default value of the isLoading state, then when you update that state, it does not affect the hook state in any way. – Cal Irvine Apr 02 '20 at 19:36
  • You just updated state, if you immediately log it you're logging state from the ***current*** render cycle, new state won't be accessible until ***next*** render cycle. – Drew Reese Apr 02 '20 at 19:46
  • Does this answer your question? [React setState not Updating Immediately](https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately) – Drew Reese Apr 02 '20 at 19:48
  • You have added the same code twice. – Rohan Agarwal Apr 02 '20 at 19:57

1 Answers1

0

State updates are async in nature. It means that if you set a new value to your state using the setter method, it's not guaranteed that you will be able to get the new value by using the state in the next lines.

React combines all the setter method executions and executes it at once.

To solve your issue, you can store the value in a variable, update the value in the setter method, but continue with the value in the variable for rest of your execution

Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35