Skip to content

When does the callback inside the setter function of the useState hook execute? #5982

@nelvko

Description

@nelvko

The React documentation describes the setter function of the useState hook as follows:

  1. React waits until all code in the event handlers has run before processing your state updates.
  2. React queues this function(callback inside the setter) to be processed after all the other code in the event handler has run.
  3. 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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions