Home » Automatic Batching in React 18

Automatic Batching in React 18

React is a popular JavaScript library for building user interfaces. The version 18 of React brought some new features that make it easier to manage and organize the code.

React has introduced a new feature – batching, which will cut down the number of updates we need to make when using React’s setState(). This makes our data flow and architecture better and helps us focus on what is most important.

Batching is a great solution for server-side rendering in React. With batching, React can start emitting markup before the data has arrived for rendering. This means that the browser can start displaying something without having to wait for all of the data before it starts rendering.

This is especially useful when using React Tower where you have multiple renders happening on one page. The tower might return with a different DOM tree than you expect, but if you use batching then it will be much easier to get everything rendered properly on that page as you won’t have to re-render everything from scratch.

When it comes to React 18, batching is one of the most important introductions. It allows us to efficiently manage our component trees by batching state updates into single operations instead of many operations with each update.

We will get more control over how and when we update our data with this new concept in place!

In this article, we will talk about React 18 release and its new feature called automatic batching. This framework has been designed to help developers create more efficient React applications by grouping together a set of related tasks in batches.

Batching In React 17

React 17 batches DOM updates using requestIdleCallback instead of componentDidMount and componentWillMount lifecycle methods. The idle callback is called whenever the browser has no other work to do, which results in smoother animations, scrolling and interactivity. React 17 only supported batching for browser events and Hooks. Case in point, state updates occurred only with asynchronous operations. Consequently, native event handlers weren’t batched.

Run Below Code with React 17 or Below Version

export default function App() {
  const [increase, setIncrease] = useState(0);
  const [decrease, setDecrease] = useState(0);
  console.log('Rendering')
  const handleOnClick = () => {
    setIncrease(increase + 1);
    setDecrease(decrease - 1);
  };
  const handleOnClickAsync = () => {
    fetch('https://jsonplaceholder.typicode.com/todos/1').then(() => {
      setIncrease(increase + 1);
      setDecrease(decrease - 1);
    });
  };
  return <>
    <button onClick={() => { handleOnClickAsync(); }}> Click Me! </button> {increase} {decrease}
  </>
}

Output

Console.log(“Rendering”) Run Two Times on one Click

Run Below Code with React 18

export default function App() {
  const [increase, setIncrease] = useState(0);
  const [decrease, setDecrease] = useState(0);
  console.log('Rendering')
  const handleOnClick = () => {
    setIncrease(increase + 1);
    setDecrease(decrease - 1);
  };
  const handleOnClickAsync = () => {
    fetch('https://jsonplaceholder.typicode.com/todos/1').then(() => {
      setIncrease(increase + 1);
      setDecrease(decrease - 1);
    });
  };
  return <>
    <button onClick={() => { handleOnClickAsync(); }}> Click Me! </button> {increase} {decrease}
  </>
}

Output

Console.log(“Rendering”) Run One Times on one Click

How To Stop Automatic Batching?

I can’t believe what an amazing time-saver it must be to use batching. But there may be times where we need to prevent this from happening. As you might have guessed, React provides a method named flushSync() that can be used to trigger a re-render for an update to a specific state.

How Does Flush Sync Work?

Essentially, this just needs to be imported with the following syntax:

import { flushSync } from 'react-dom';

One way to do this is by calling the method inside an event handler and placing your state update inside the body of flushSync().

const handleClick = () => { flushSync(() => { setClicked(!clicked); // react will create a re-render here }); 
setCount(count + 1); // react will create a re-render here};

When we call setCount, React will update the DOM twice. The first time it updates as soon as flushSync() occurs and again in order to track the count increase.

Related Blogs

  • Ajax
    December 6, 2021

    What is AJAX

    AJAX stands for Asynchronous JavaScript and XML. It is a web development technique that is used to create dynamic webpages.

  • web-designing-trends
    May 6, 2022

    Web Designing Trends in 2022

    Website designing trends are constantly changing. The good news is that it's easier than ever to keep up with the latest trends. In this article, we will g ....

  • express js
    December 8, 2021

    What is Express JavaScript

    Express is a web application framework that helps you build the web apps of your dreams. It was originally developed by TJ Holowaychuk and some of the core ....