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;