简体   繁体   中英

React Hooks Re-renders

I have a functional component that has two pieces of state:

 let [data, setData] = useState([]);
 let [loading, setLoading] = useState(false);

I also have a simple useEffect hook that calls a function that returns a promise:

 useEffect(() => {
    someFunctionThatReturnsAPromise().then({
            console.log("Before setData");
            setData(dataFromFetch);
            console.log("After setData");
            console.log("Before setLoading");
            setLoading(true);
            console.log("After setLoading");
        }
        );
},[]);




return (
        <div>
            console.log("Hey i rendered");
        </div>
    );

Seeing as i have an empty dependency array ( [] inside useEffect ), this useEffect will only run once. My question is:

Seeing as setData causes the component to re-render, shouldn't as soon as the code reaches setData(dataFromFetch); , shouldn't the execution stop? In my console log, the this is what gets printed:

Hey i rendered
Before setData
Hey i rendered
After setData
Before setLoading
Hey i rendered
After setLoading

I expected something like:

Hey i rendered
Before setData
Hey i rendered

Why does the execution continue even after the component re-renders? Where can i go to read up on something like this?

setState is added to the javascript event stack and is asynchronous by nature and useEffect is being executed fully via the javascript call stack regardless of other async functions added to the end of the stack (such as console.logs and setStates)

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Heres an article on the event queue/javascript lifecycle that may explain better: https://flaviocopes.com/javascript-event-loop/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM