Blog>
Snippets

Optimizing React Re-renders with Batched Actions

Demonstrate how batching actions in Redux-Saga can lead to fewer React component re-renders, showcasing a before and after comparison with performance analysis.
import { put, call } from 'redux-saga/effects';
import { batch } from 'react-redux';
import { actionOne, actionTwo } from './actions';
First, we import necessary functions and actions. The 'batch' function from 'react-redux' will be used to batch actions.
// Before optimization
function* sagaWorker() {
  yield put(actionOne());
  yield put(actionTwo());
}
This is an example of a Saga worker before optimization. Each action dispatch triggers a potential re-render in React components.
// After optimization
function* optimizedSagaWorker() {
  yield call(batch, function* () {
    yield put(actionOne());
    yield put(actionTwo());
  });
}
This is an optimized version of the Saga worker using 'batch'. It reduces the number of re-renders by combining multiple actions into a single update cycle.
/* Performance Analysis*/
// Before: Each 'put' could cause a re-render, leading to 2 re-renders.
// After: Using 'batch', both actions result in a single re-render, optimizing performance.
This comment explains the performance improvement. Initially, there could be two re-renders due to individual actions. After batching, these actions result in a single re-render, enhancing performance.