Avoid React Re-Renders with Automatic Batching

React 18 introduces ‘Automatic Batching’ to boost performance

What is Batching?

Batching occurs in React when it groups multiple state updates into a single re-render for better performance.

For example, if you have two state updates — for example, setCount and setFlag — in the same click event handler, React will render this component only once. See the below example for an instance of when this would occur:

const App = () => {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
  const handleClick = () => {
setCount(count + 1);
setFlag(!flag);
};
  return (
<div>
<button onClick={handleClick}>Click here!</button>
<h1>{count}</h1>
<h1>{`${flag}`}</h1>
</div>
);
};

Earlier versions of React batched multiple state updates only inside React-specific event handlers such as onClick or onChange.

However, batching is not applied to cases like promises, setTimeout, native event handlers, and so on by default.

Automatic Batching

Starting from React 18, there is a new root API called createRoot which allows you to use all the concurrent features of React 18.

Enabling createRoot

Once you’ve upgraded to React v18, you can make use of createRoot by finding the file in our project that has the following code (usually index.js):

const rootNode = document.getElementById('root')
ReactDOM.render(<App />, rootNode)
// or if you're using v16 it might be...
ReactDOM.render(<App />, document.getElementById("root"));

And changing it to:

ReactDOM.createRoot(rootNode).render(<App />);

Note: Automatic Batching works only with createRoot.

React 18 will batch updates automatically, no matter where the updates happen.

Let’s jump into an example to understand different use cases of batching:

In setTimeout

const handleClick = () => {
setTimeout(() => {
setCount(count + 1);
setFlag(!flag);
}, 1000);
};

Fetch call

const handleClick = () => {
fetch("URL").then(() => {
setCount(count + 1);
setFlag(!flag);
});
};

Native event handlers

const el = document.getElementById("button");
el.addEventListener("click", () => {
setCount(count + 1);
setFlag(!flag);
});

In each of the above cases, both state update calls will be batched by React at once. This avoids re-rendering components with a partially updated state in any event.

In some cases, where we do not wish to batch state, we can use flushSync API from react-dom. These are useful when one updated state is required before updating another state.

import { flushSync } from 'react-dom'; 

function handleClick() {
flushSync(() => {
setCounter(c => c + 1);
});
// React has updated the DOM by now
flushSync(() => {
setFlag(f => !f);
});
// React has updated the DOM by now
}

Conclusion

Avoiding re-renders is one of the biggest challenges in React. Hence, automatic batching is one such best feature to use in our application.

Write scaleable, modular components with Bit

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn more


Avoid React Re-Renders with Automatic Batching was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Nivetha Krishnan

React 18 introduces ‘Automatic Batching’ to boost performance

What is Batching?

Batching occurs in React when it groups multiple state updates into a single re-render for better performance.

For example, if you have two state updates — for example, setCount and setFlag — in the same click event handler, React will render this component only once. See the below example for an instance of when this would occur:

const App = () => {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
  const handleClick = () => {
setCount(count + 1);
setFlag(!flag);
};
  return (
<div>
<button onClick={handleClick}>Click here!</button>
<h1>{count}</h1>
<h1>{`${flag}`}</h1>
</div>
);
};

Earlier versions of React batched multiple state updates only inside React-specific event handlers such as onClick or onChange.

However, batching is not applied to cases like promises, setTimeout, native event handlers, and so on by default.

Automatic Batching

Starting from React 18, there is a new root API called createRoot which allows you to use all the concurrent features of React 18.

Enabling createRoot

Once you’ve upgraded to React v18, you can make use of createRoot by finding the file in our project that has the following code (usually index.js):

const rootNode = document.getElementById('root')
ReactDOM.render(<App />, rootNode)
// or if you're using v16 it might be...
ReactDOM.render(<App />, document.getElementById("root"));

And changing it to:

ReactDOM.createRoot(rootNode).render(<App />);

Note: Automatic Batching works only with createRoot.

React 18 will batch updates automatically, no matter where the updates happen.

Let’s jump into an example to understand different use cases of batching:

In setTimeout

const handleClick = () => {
setTimeout(() => {
setCount(count + 1);
setFlag(!flag);
}, 1000);
};

Fetch call

const handleClick = () => {
fetch("URL").then(() => {
setCount(count + 1);
setFlag(!flag);
});
};

Native event handlers

const el = document.getElementById("button");
el.addEventListener("click", () => {
setCount(count + 1);
setFlag(!flag);
});

In each of the above cases, both state update calls will be batched by React at once. This avoids re-rendering components with a partially updated state in any event.

In some cases, where we do not wish to batch state, we can use flushSync API from react-dom. These are useful when one updated state is required before updating another state.

import { flushSync } from 'react-dom'; 

function handleClick() {
flushSync(() => {
setCounter(c => c + 1);
});
// React has updated the DOM by now
flushSync(() => {
setFlag(f => !f);
});
// React has updated the DOM by now
}

Conclusion

Avoiding re-renders is one of the biggest challenges in React. Hence, automatic batching is one such best feature to use in our application.

Write scaleable, modular components with Bit

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

Bit offers a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components.
Give it a try →

An independently source-controlled and shared “card” component. On the right => its dependency graph, auto-generated by Bit.

Learn more


Avoid React Re-Renders with Automatic Batching was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Nivetha Krishnan


Print Share Comment Cite Upload Translate Updates
APA

Nivetha Krishnan | Sciencx (2022-01-05T19:06:34+00:00) Avoid React Re-Renders with Automatic Batching. Retrieved from https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/

MLA
" » Avoid React Re-Renders with Automatic Batching." Nivetha Krishnan | Sciencx - Wednesday January 5, 2022, https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/
HARVARD
Nivetha Krishnan | Sciencx Wednesday January 5, 2022 » Avoid React Re-Renders with Automatic Batching., viewed ,<https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/>
VANCOUVER
Nivetha Krishnan | Sciencx - » Avoid React Re-Renders with Automatic Batching. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/
CHICAGO
" » Avoid React Re-Renders with Automatic Batching." Nivetha Krishnan | Sciencx - Accessed . https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/
IEEE
" » Avoid React Re-Renders with Automatic Batching." Nivetha Krishnan | Sciencx [Online]. Available: https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/. [Accessed: ]
rf:citation
» Avoid React Re-Renders with Automatic Batching | Nivetha Krishnan | Sciencx | https://www.scien.cx/2022/01/05/avoid-react-re-renders-with-automatic-batching/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.