I read in this article that upon a state change, React schedules a re-render but doesn't execute it right away; rather it will kick it off at an optimal time. I am trying to understand if and how this might take place in the context of the current function execution, which has initiated the state change. If a function calls useState() but still has several lines of code left, I can see one of several possibilities happening:
- will it execute those lines first then kick off the re-render?
- will it do the re-render right away and then get back to executing the remainder of the function?
- will it re-render asynchronously at some point within the function execution that it deems most performant (and might be a different point each time)?
- will it re-render concurrently right away at the same time the function continues its execution?
To phrase my question in a different way, take this example code (trimmed for brevity):
const CreateButton = (props) => {
const [processing, setProcessing] = useState(false);
const create = () => {
setProcessing(true);
fetch("/api/test", {
headers: {
"Content-Type": "application/json",
},
method: "post",
body: JSON.stringify(body),
})
.then(() => {
setProcessing(false);
console.log("We are not processing");
});
}
return (
<div>
{processing ? (
"Currently processing"
) : (
<input type="button" onClick={create} />
)}
</div>
);
};
We initialize the "processing" state value to false. Then in our return statement, we check whether this is true or false. Since its false, we call the "create" function, which sets processing=true. This is a change of state meaning a re-render gets scheduled. However, if you notice later in the create method we make an API request and in the subsequent .then() we set processing=false.
So, if the create() function finishes before the re-render it's possible it will just print "We are not processing" and call the create() method again. However, this re-render will have been initially invoked because we set processing=true, so we should expect it to instead print "Currently processing".
Alternately, if the re-render runs right away and then execution of the create() method continues, the flow would make sense here as it does what we would expect. This seems to be the outcome when I test this code but I want to make sure I'm fully understanding what React is doing under the hood.