React-redux: Clarification required on batch() documentation

Created on 26 Nov 2020  路  1Comment  路  Source: reduxjs/react-redux

Hi all -- first of all, thank you for your work on this library. I have a question based on an example from the documentation I ran last night.

What is the current behavior?

According to the 7.2 documentation for batch(), this code should result in two renders if batch() is not used:

import { batch } from 'react-redux'

function myThunk() {
  return (dispatch, getState) => {
    // should only result in one combined re-render, not two
    batch(() => {
      dispatch(increment())
      dispatch(increment())
    })
  }
}

However, when I removed batch() in this case, the code still resulted in one render.

You can see that in action here with the incrementByTwo() action creator:

https://codesandbox.io/s/goofy-pare-6nncg

What is the expected behavior?

Based on the documentation, I would expect removing batch() in this circumstance to result in two renders. Can anyone advise me as to why this is not happening?

Thanks!

Most helpful comment

Because those thunks are running synchronously inside of a React event handler. Thus, they are _already_ running inside of a batch() call, albeit one that's internal to React's own event handling.

See my post at https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#render-batching-and-timing for a complete explanation of how React handles batching.

>All comments

Because those thunks are running synchronously inside of a React event handler. Thus, they are _already_ running inside of a batch() call, albeit one that's internal to React's own event handling.

See my post at https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#render-batching-and-timing for a complete explanation of how React handles batching.

Was this page helpful?
0 / 5 - 0 ratings