I'm seeing something unexpected in this code example here: https://codesandbox.io/s/react-redux-application-forked-lb7zk?file=/src/pages/DashboardPage.js:415-452
I'm logging the change of the x
variable (that comes from redux state).
I dispatch 2 actions that would cancel each other:
x
starts as 1- first dispatch changes it to:
x=2
- second dispatch changes it back to:
x=1
I was expecting to see 3 console.logs, one for the initial render, and two more for each change described above. But instead I'm only getting 1, the one for the initial render. It seems that since they all happen in a sudden, redux seems to batch the actions so the state doesn't really changes in this case.
This really makes me doubt, I'd like to understand what's going on., Is this what's going on?
CodePudding user response:
Edit: React batches state updates that occur in event handlers and lifecycle methods. Thus, if you update state multiple times in UseEffects hook, React will wait for event handling to finish before re-rendering.
You are correct. What's going on is that its running all 3 actions once and console.log() is running after the state is updated. It's essentially running this:
useEffect(() => {
dispatch(test(2));
dispatch(test(1));
console.log("Did X change?", x);
}, [dispatch, x]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I believe the reason is automatic batching in React. As we know "React groups multiple state updates into a single re-render for better performance".
For more information, please check out this great discussion in React 18 Group: https://github.com/reactwg/react-18/discussions/21
I hope it's useful to help you to discovery your problem.