When the state called loading is set to true and a re-render of the component is caused, where does the function continue? Does it run console.log(1) again, just that it's that fast that I can't track it? Or does it contiune with console.log(2)? Or is the re-render happening after console.log(2) while the asynchronous operation is running? The same question appears regarding the moment loading is set to false again. Will it re-render after console.log(3) and console.log(4) have run or between those as the order in the code would suppose?
If there was no async operation running between the state changes, would the Spinner even appear at some point?, or would the entire function run before it re-renders and therby the state true not even trigger a re-render, because the state changes get "bundled" which would mean that it would only re-render when the state is set to false again?
Sorry for the complicated formulation but I don't know any other way to express myself. I struggle with the idea that a re-render means that the entire functional component is re-run, because a function call could thereby be interrupted. I just don't undestand how and where it conitunes and if that is consistent, because it should be IMO.
´´´ export default function IndexComponent() {
const [loading, setLoading] = useState(false)
const doSomething = async () => {
console.log(1)
setLoading(true) //re-renders and Spinner appears
console.log(2)
await new Promise(resolve => setTimeout(resolve, 5000));
console.log(3)
setLoading(false)//re-renders and Spinner disappears
console.log(4)
}
return (
<div>
<button onClick={doSomething}>Login</button>
{loading && <div>Spinner</div>}
</div>
)
} ´´´