-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Description
The React documentation describes the setter function of the useState hook as follows:
- React waits until all code in the event handlers has run before processing your state updates.
- React queues this function(callback inside the setter) to be processed after all the other code in the event handler has run.
- After the event handler completes, React will trigger a re-render.During the re-render, React will process the queue.Updater functions run during rendering.
Here is the reference address of the official documentation
Here's the pseudo code for the test:
function handleClick() {
console.log('start')
setCount(count => {
console.log('set');
return count + 1;
})
console.log('end')
}
According to the official React documentation, when handleClick is triggered, it first prints "start", then it puts the callback that include "console.log('set')" into the queue (without executing it), then prints "end". After all the synchronous code in the event handler handleClick has finished running, the functions inside the queue will be executed.
In theory, the printing order should be "start", "end", "set".
However, in practice, the printing order was "start", "set", "end".
documentation provides an example where the functions inside the setCount are all queued up, not just the return value. This means that the console.log statements inside the callback functions are also queued up.
Why is the actual print order different from what I understand?