Skip to content

Bug: out of order application of useState changes #25129

Closed as not planned
Closed as not planned
@zuozp8

Description

@zuozp8

After updating my app to React 18 I had problem with inconsistent state from useState

I created code example with the problem:

  • I have 2 states const [done, setDone] = useState(false); (inside hook) and const [ids, setIds] = React.useState([])
  • I call setIds([1,2,4]) (inside await, but it's executed immediately, as we see in console) and then setDone(true)
  • then component is rerendered with updated done but original ids
  • then component is rerendered, but with both states updated

React version: 18.2.0, 18.3.0-next
Link to code example: https://codesandbox.io/s/purple-dust-ww9hjm?file=/src/index.jsx
Smaller repro: https://codesandbox.io/s/cocky-fermat-qoiel3 (from eps1lon's comment)

The current behavior

In the example after clicking run:
Inner is rerendered with done: true, but without updated ids.
FormikLike is created with empty ids.
[] is displayed under button.

The expected behavior

First Inner rerender should have updated ids state.
FormikLike should be created with non-empty ids.
[1,2,4] is displayed under button.

It workied this way in React 17.

In https://stackoverflow.com/a/48610973 @gaearon wrote:

But can you trust React to update the state in the same order as setState is called for the same component?

Yes.

Answer was for class components, but I hope the same is true for multiple useState hooks in single function component.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bugType: Bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions