Blog>
Snippets

Batching Actions for Performance Gain

Illustrate how to batch multiple dispatch calls to reduce the number of render cycles and optimize performance in Redux-based applications.
import { batch } from 'react-redux';

// Wrap your dispatch calls in the batch function to combine them
// so that only a single render is needed for all of them.
batch(() => {
  dispatch(updateUser(user));
  dispatch(fetchPosts());
  dispatch(setLoading(false));
});
This code imports the batch function from react-redux and uses it to wrap multiple dispatch calls. The batch function ensures that React only re-renders once after all the actions have been dispatched, rather than re-rendering after each individual dispatch call. This can lead to performance gains, especially when dispatching many actions in a short amount of time.