Blog>
Snippets

Batching Updates to Reduce Render Cycles

Explain how to batch state updates using TanStack Store's utilities or React's capabilities to wrap multiple state updates in a single render cycle, for scenarios like initializing the application state from an external data source.
import { unstable_batchedUpdates } from 'react-dom';

// Fetch external data and initialize state
fetchDataFromAPI().then(data => {
  unstable_batchedUpdates(() => {
    setState(data.stateOne);
    setAnotherState(data.stateTwo);
  });
});
This code snippet demonstrates how to use React's unstable_batchedUpdates from react-dom to wrap multiple state updates in a single render cycle. This approach is especially useful when initializing the application state from an external data source, such as an API. By calling setState and setAnotherState inside unstable_batchedUpdates, React batches these updates into a single render, optimizing performance.
import { batch } from 'react-redux';

// Assuming 'dispatch' is available from useDispatch() hook from react-redux
batch(() => {
  dispatch(updateActionOne(payloadOne));
  dispatch(updateActionTwo(payloadTwo));
});
This example uses the batch utility from react-redux to group multiple redux dispatch calls into a single render cycle. This technique is beneficial in scenarios where multiple state updates are derived from a single asynchronous operation, optimizing the application's rendering performance by reducing the number of re-renders.