Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Data Fetching Libraries and React Hooks
Next article icon

What is Automatic Batching in React 18

Last Updated : 14 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

React 18 includes great features including automatic batching, which enhances rendering effectiveness and results in significant gains for programmers and users.

This article is going to explain what batching is, how it worked before in React, and how our lives have been changed by automatic batching.

Table of Content

  • What is Batching?
  • Batching in React Before React 18
  • What is Automatic Batching in React 18?
  • Benefits of Automatic Batching
  • Automatic Batching in Action
  • When Automatic Batching Might Not Apply
  • Advanced Use Cases and Best Practices
  • Conclusion

What is Batching?

In the context of React, batching refers to the strategy of grouping multiple state updates before triggering a re-render of the component. This optimization is essential because each re-render can be computationally expensive, especially in complex components with a large virtual DOM tree.

Batching in React Before React 18

In earlier versions of React, batching was primarily limited to state updates that occurred within React event handlers. Consider the following code example:

Here's a simple example:

function handleClick() {
setCount(count + 1); // Update 1
setIsVisible(true); // Update 2
}

React would intelligently recognize that these updates occur within the same event handler and batch them together, resulting in a single re-render of the relevant component.

However, state updates originating outside of event handlers, such as updates within promises, timeouts, or native event listeners, would not be batched by default. Let's illustrate this:

setTimeout(() => {
setCount(count + 1); // Update 1
setIsVisible(false); // Update 2
}, 1000);

In React 17 and prior, this code could potentially trigger two separate re-renders, which might become a performance bottleneck in applications with frequent asynchronous updates.

What is Automatic Batching in React 18?

React 18 fundamentally changes how React handles state updates by introducing automatic batching. The key difference is that batching now extends beyond just event handlers. In most cases, regardless of where a state update originates, React will attempt to batch it together with other pending updates.

Let's revisit our previous timeout example:

setTimeout(() => {
setCount(count + 1); // Update 1
setIsVisible(false); // Update 2
}, 1000);

In React 18, these updates within the timeout will generally be batched together, ensuring that the component re-renders only once after both states have been modified.

Benefits of Automatic Batching

  • Performance Optimization: By minimizing re-renders, automatic batching significantly improves UI performance, especially in complex applications with frequent state updates.
  • Simplified Code: You no longer need to worry about manually wrapping state updates for batching; React handles it seamlessly.
  • Enhanced User Experience: Smoother, more responsive interfaces resulting from better performance contribute directly to a more satisfying user experience.

Automatic Batching in Action

Let's examine some common scenarios where automatic batching benefits React applications:

  • Multiple State Updates Within a Handler:
function handleClick() {
setCount(count + 1);
setIsLoading(true);
setIsError(false);
}
  • Asynchronous Operations (Promises/setTimeout):
fetch('/api/data')
.then(response => response.json())
.then(data => {
setData(data);
setIsLoading(false);
});
  • Handling User Input: Consider form inputs where each keystroke can trigger a state update:
function handleInputChange(event) {
setSearchTerm(event.target.value);
}

Automatic batching ensures that React doesn't re-render excessively as the user types.

When Automatic Batching Might Not Apply

It's important to note that while automatic batching is incredibly powerful, there might be rare instances where it doesn't occur as expected. These often involve interactions with older libraries or code that hasn't been fully adapted to React 18's concurrency model.

Here is a hypothetical scenario:

// An older library with its own event system 

someOldLibrary.addEventListener('update', () => {
setCount(count + 1);
});

Updates generated from within external event systems may not always be automatically batched. If you experience such cases, consult the React documentation for guidance on ensuring optimal behavior and how you might leverage React's `unstable_batchedUpdates` API for finer control.

Advanced Use Cases and Best Practices

While automatic batching covers most everyday situations, knowing a few additional techniques can be helpful:

  • Forcing a Re-render: At times, you might need to force a re-render immediately, bypassing the batching mechanism. React provides the flushSync utility for this:
import { flushSync } from 'react-dom';

flushSync(() => {
setCount(count + 1);
});

Use `flushSync` judiciously, as it can negatively impact performance if overused.

  • Understanding `useTransition`: React 18's `useTransition` hook is designed for separating urgent and non-urgent updates. Urgent updates (like responding to direct user input) should proceed as normal, while non-urgent updates (like fetching secondary data) can be marked as transitions. Automatic batching works in conjunction with transitions to ensure smoother experiences.

Conclusion:

Automatic batching represents a valuable addition to React's toolkit for building high-performance web applications. By intelligently grouping state updates, React 18 minimizes re-renders, resulting in smoother interactions, simplified code, and an enhanced user experience. As you adopt React 18, you'll likely reap the benefits of automatic batching without requiring significant changes to your existing codebase.


Next Article
Data Fetching Libraries and React Hooks

V

vikash95
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Questions

Similar Reads

  • Top Features Coming in React 18
    Are you a web developer? If yes, then you must know that React is a very popular JavaScript library. There are a huge number of companies which are working on it. Every web technology gets an update gradually. The React team has already started working on React 18 which will be one of the major vers
    4 min read
  • What is the React Context API?
    In the React ecosystem, as your application grows, passing data down through component hierarchies can become cumbersome. This is where the Context API steps in, providing a centralized way to manage state across components. Table of Content What is the Context API?How Context API Works:Steps to Cre
    4 min read
  • Data Fetching Libraries and React Hooks
    Data fetching libraries like React Query and React Hooks simplify how developers fetch and manage data in React applications. These tools provide easy-to-use functions like 'useQuery' and 'SWR' that streamline API interactions and state management, improving code readability and reducing boilerplate
    6 min read
  • What is Memoization in React ?
    Memoization is a powerful optimization technique used in React to improve the performance of applications by caching the results of expensive function calls and returning the cached result when the same inputs occur again. In this article, we will learn more about the concept of memoization and its
    6 min read
  • What is ComponentWillMount() method in ReactJS ?
    ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle method is an ideal choice when it comes to updating business logic, app configuration updates, and API calls.  PrerequisitesReact JSReact JS class componentsComponentWillMoun
    4 min read
  • Accessing state in setTimeout React.js
    We frequently deal with timeouts when developing different applications with React. A setTimeout method enables us to invoke a function after a particular interval. However, implementing the conventional setTimeout in React can be difficult. Prerequisites:NodeJS or NPMReact JSsetTimeoutSteps to Crea
    3 min read
  • Additional Built-in Hooks in React
    Hooks are functions that allow you to "hook" into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes. We will discuss the various
    6 min read
  • Form Handling with React Hooks
    Forms are an important part of web development. Form handling is a crucial user interaction for websites. React hooks provide a concise and very efficient way to handle the state of the form as the user interacts with the form fields. There are mainly two react hooks for this purpose. useState:- use
    4 min read
  • How to Implement Caching in React Redux applications ?
    Caching is the practice of storing frequently used or calculated data temporarily in memory or disk. Its main purpose is to speed up access and retrieval by minimizing the need to repeatedly fetch or compute the same information. By doing so, caching helps reduce latency, conserve resources, and ult
    3 min read
  • New DOM Methods in React 18
    React 18 has introduced several exciting features and improvements, including new DOM methods that enhance the developer experience. In this article, we will explore these new methods, discuss their syntax, and provide step-by-step instructions on how to integrate them into your React applications.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences