I am getting two diffrent orders of console.log prints based on wheater i am using a promise or not.
The state:
let [data,setData] = useState(1);
When using promise:
let asyncFunk = async () => {
return "Asd";
};
useEffect(() => {
asyncFunk().then((result) => {
console.log("BEFOR SET DATA " +data);
setData(prev => prev +1 );
console.log("AFTER SET DATA " +data);
});
},[]);
return (
<div>
{console.log("Data in return " + data)}
</div>
);
}
The console.log print order is:
Data in return 1
BEFOR SET DATA 1
Data in return 2
AFTER SET DATA 1
So when the setData() is hit, the component re-renders, and the console.log from the return gets called BEFORE the console.log after the setData().
When i remove the async function:
useEffect(() => {
console.log("BEFOR SET DATA " +data);
setData(prev => prev +1 );
console.log("AFTER SET DATA " +data);
},[]);
return (
<div>
{console.log("Data in return " + data)}
</div>
);
}
The console.log print order is:
Data in return 1
BEFOR SET DATA 1
AFTER SET DATA 1
Data in return 2
When the async function is removed, the useEffect finishes first, and also prints the old state value as well, then the console.log from the return gets printed.
Any idea whats going on here and why this is the order the prints are happening?