Consider a button callback listener in React Functional components defined as below -
Here's the codesandbox link to repro this.
const [setCtr, ctr] = useState(0);
const btnClicked = () => {
console.log("button callback");
setCtr((x) => {
console.log("setCtr executed...");
return x + 1;
});
console.log("button callback ends");
};
When I click on the button, the first time, setCtr executes synchronously but after that it always (tried 20 times) runs asynchronously.
Here's the output for first button click
button callback
setCtr executed...
button callback ends
Here's the output for subsequent button clicks
button callback
button callback ends
setCtr executed...
button callback
button callback ends
setCtr executed...
button callback
button callback ends
setCtr executed...
button callback
button callback ends
setCtr executed...
This is confusing. How exactly does the set function in useState work?
If it was truly an async function, we should always get button callback ends before setCtr executed....
This makes me think sometimes it behaves as synchronous function, while sometimes as asynchronous function.