Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Additional updater function call is not ignored in Strict Mode #28700

Closed
ayloncarrijo opened this issue Apr 1, 2024 · 1 comment
Closed

Comments

@ayloncarrijo
Copy link

ayloncarrijo commented Apr 1, 2024

When calling a setState with an updater function inside a useEffect, the additional call made in Strict Mode is not ignored, producing an unexpected state. The same behavior is NOT seen in React 17. From the docs:

In Strict Mode, React will call your updater function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.

React version: 18

Steps To Reproduce

  1. Create a state that holds a number.
  2. Include a call to its setState inside a useEffect, which adds +1 to the previous value.
  3. Note that React will NOT ignore the additional call made in Strict Mode and will sum twice.

Link to code example: https://codesandbox.io/p/sandbox/zealous-thompson-htqfst?file=%2Fsrc%2FApp.js%3A16%2C1

The current behavior

It is not ignoring the additional call to setState. In the example above, the result is 2.

The expected behavior

It should ignore the additional call to setState. In the example above, the result should be 1.

@ayloncarrijo ayloncarrijo added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 1, 2024
@eps1lon
Copy link
Collaborator

eps1lon commented Apr 2, 2024

In React 18, StrictMode started double invoking effects. This is why you're seeing an additional call of the state updater function because we're invoking the function passed to useEffect again which calls setState again.

The docs describe the intention behind this change in more detail: https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-re-running-effects-in-development

@eps1lon eps1lon closed this as not planned Won't fix, can't repro, duplicate, stale Apr 2, 2024
@eps1lon eps1lon added Resolution: Expected Behavior and removed Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug labels Apr 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants