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

When using setState nesting, run log setState will execute multiple times #124

Open
JiaChaoFei opened this issue Oct 21, 2023 · 1 comment

Comments

@JiaChaoFei
Copy link

JiaChaoFei commented Oct 21, 2023


const [state, setState] = useImmer({
  count: 0,
});

const handleAdd = () => {
  setState((draft) => {
    draft.count += 1;
  });
};

const setValue = () => {
  console.log("run setValue")
  setState((draft) => {
    console.log("run setState");
    if (draft.count < 1) {
      handleAdd();
    } else {
      draft.count -= 1;
    }
  });
};

setValue();

log:
run setValue;
run setState;
run setState;

When using setState nesting, run log setState will execute multiple times

@Ashish-simpleCoder
Copy link

Hi @JiaChaoFei,
I think this might be happening in development mode only, as development mode runs the code in React.StrictMode.
So try to turn off StrictMode and test it again.

If not fixed, then you could just share the code-sandbox of your code to help you out.

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

No branches or pull requests

2 participants