reactjs / reactjs/react.dev

setState() callback function: potential confusion of call order

Open
#691 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

This paragraph from the React.Component reference page:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

can create the impression that instead of doing:

this.setState({ value: 5 });
console.log(this.state.value); // => not necessarily 5

you can use the callback function to safely read the state back:

this.setState({ value: 5 }, () => console.log(this.state.value)); // => "guaranteed" 5

(especially if you draw a parallel between the callback function and the updater function)

and it may actually work in some cases where there's no setState batching, but as more calls get batched in the future, these constructs may generate unintended side-effects.

Instead, we could clarify that all callback functions for a batch of setState() calls get called after the entire batch has been processed.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the setState section of the React.Component reference page linked in the issue. Review the wording around callbacks and batching, then update it so callback timing and the state available after a batch are unambiguous; done means the examples cannot suggest that a callback observes only its individual update.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.