Skip to content

Update guidance on when updater functions are needed for useState to account for transitions#8456

Open
captbaritone wants to merge 1 commit into
reactjs:mainfrom
captbaritone:usestate-updater-deepdive-clarification
Open

Update guidance on when updater functions are needed for useState to account for transitions#8456
captbaritone wants to merge 1 commit into
reactjs:mainfrom
captbaritone:usestate-updater-deepdive-clarification

Conversation

@captbaritone
Copy link
Copy Markdown

The existing deep dive on when to use updater functions vs the state variable from render predates the introduction of transitions and makes strong claims which are no-longer fully true. Specifically (emphasis mine):

React always makes sure that for intentional user actions, like clicks, the age state variable would be updated before the next click.

This is not "always" true, since the state update in the intentional user action may have been wrapped in a startTransition.

This means there is no risk of a click handler seeing a "stale" age at the beginning of the event handler.

There is some risk since the state may be updating as part of transition.


This PR attempts to restructure the guidance to account for this added complexity while keeping the mental overhead for users as minimal as possible while staying honest.

The existing DeepDive overstated the guarantee that state is always
up-to-date before the next user action. This is not true when the state
variable has been updated inside a Transition elsewhere in the app, or
when multiple updates happen in the same event handler.

Restructure to present both cases together and contrast the two
approaches (reading the state variable vs. using an updater).
@github-actions
Copy link
Copy Markdown

Size changes

Details

📦 Next.js Bundle Analysis for react-dev

This analysis was generated by the Next.js Bundle Analysis action. 🤖

This PR introduced no changes to the JavaScript bundle! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant