DEV Community

duccadhv1
duccadhv1

Posted on

What is React batching state?

What is React batching state?

Batching is when React groups multiple state updates into a single re-render for better performance. For example, if you have two state updates inside of the same click event, React has always batched these into one re-render.

However, in React 17 and prior, updates inside promises, setTimeout, native event handlers, or any other event were not batched in React by default. This means that each state update would trigger a separate re-render, which could cause unnecessary UI flickering and performance issues.

React 18 introduces automatic batching for all state updates, regardless of where they occur. This means that React will automatically batch any state updates that happen within the same event loop tick into one re-render. This makes your code more consistent and predictable, and improves the performance and user experience of your app.

How does React batching state work?

React batching state works by using a scheduler to queue up state updates and flush them at the appropriate time. The scheduler uses a heuristic to determine when to flush the updates based on the browser's event loop, the user's interaction, and the priority of the updates.

The scheduler also allows you to control the priority of your updates using the new startTransition and useDeferredValue APIs. These APIs let you mark some updates as low-priority or deferred, which means they will be batched and rendered later, while other updates are rendered immediately. This can help you avoid blocking the main thread and improve the perceived performance of your app.

Why is React batching state important?

React batching state is important because it can help you optimize the performance and user experience of your app. By batching multiple state updates into one re-render, you can:

  • Reduce the number of DOM operations and layout calculations, which can improve the speed and efficiency of your app.

  • Avoid unnecessary UI flickering and jankiness, which can improve the smoothness and responsiveness of your app.

  • Simplify your code logic and avoid race conditions, which can improve the readability and maintainability of your code.

Here are some examples of how to use React batching state in your code:

Example 1: Batching multiple state updates inside a promise

In this example, we have a button that fetches some data from an API and updates two states: loading and data. In React 17 and prior, each state update would trigger a separate re-render, which could cause UI flickering. In React 18, both state updates are batched into one re-render, which makes the UI smoother.

import { useState } from "react";

function App() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);

  function handleClick() {
    setLoading(true); // set loading to true
    fetch("https://jsonplaceholder.typicode.com/todos/1").then((response) => response.json()).then((json) => {
   setLoading(false); // set loading to false
   setData(json); // set data to json
  });
}

return (
 <div>
  <button onClick={handleClick}>Fetch Data</button>
  {loading && <p>Loading...</p>}
  {data && <p>{data.title}</p>}
 </div>
 );
}
Enter fullscreen mode Exit fullscreen mode

Example 2: Batching multiple state updates inside a setTimeout

In this example, we have a button that increments two counters: count1 and count2. The first counter is incremented immediately, while the second counter is incremented after one second using setTimeout. In React 17 and prior, each state update would trigger a separate re-render, which could cause UI inconsistency. In React 18, both state updates are batched into one re-render, which makes the UI consistent.

import { useState } from "react";

function App() {
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);

  function handleClick() {
    setCount1((prev) => prev + 1); // increment count1 immediately
    setTimeout(() => {
    setCount2((prev) => prev + 1); // increment count2 after one second
  }, 1000);
}

return (
  <div>
    <button onClick={handleClick}>Increment Counters</button>
    <p>Count1: {count1}</p>
    <p>Count2: {count2}</p>
  </div>
 );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

React batching state is a feature that improves the performance and user experience of React applications by grouping multiple state updates into a single re-render. It works by using a scheduler to queue up state updates and flush them at the appropriate time. It also allows you to control the priority of your updates using the new startTransition and useDeferredValue APIs. React batching state is important because it can help you reduce the number of DOM operations, avoid unnecessary UI flickering, and simplify your code logic.

Top comments (0)