1

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:

  1. x starts as 1
  2. first dispatch changes it to: x=2
  3. 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?

Matias
  • 527
  • 1
  • 4
  • 19

2 Answers2

2

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.

Related Question

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]);
  • 1
    I believe OP is asking why this happens though – Sinan Yaman Oct 15 '21 at 14:36
  • Yeah, exactly, I really don't get why it happens. Cause I've noticed there's another function for batching dispatches: https://react-redux.js.org/api/batch But I'm not using that, so I can't make sense of it – Matias Oct 15 '21 at 14:44
  • 1
    Thanks for pointing that out. I edited it to try and explain better. – Casey Knight Oct 15 '21 at 14:44
  • 1
    while the above answer is right about batch update. but one question still remains why the console.logs are not printed twice. The answer is that the useEffect compare the current value with previous value [refer](https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects). Since the initial value was 1 and at the end the new value is also 1, the next useEffect function call is skipped – Himanshu Patil Oct 15 '21 at 15:38
1

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.

Long Nguyen Duc
  • 1,317
  • 1
  • 8
  • 13