This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Understanding React Batching for Performance Optimization

  • ReactJS
  • October 25, 2024

Share On :

Introduction

React automatic batching is a powerful optimization technique in React that groups multiple state updates into a single render. By batching updates, React minimizes the number of re-renders, improving performance and ensuring smoother UI interactions. Batching occurs automatically in event handlers and lifecycle methods, allowing developers to write efficient code without manual intervention. This optimization is especially useful in complex applications where multiple state changes occur rapidly, as it reduces unnecessary renders and boosts overall application efficiency. Understanding React batching is key to building fast and responsive React applications.

Prerequisites
  • Node.js and npm
  • React
Understanding React Automatic Batching : Optimizing State Updates

Why React Automatic Batching Matters for Enhancing Application Performance

In traditional React state updates, each call to setState triggers a re-render of the component where the state is defined. This means that when multiple state updates are executed in quick succession, React may initiate a separate re-render for each update. The challenges include:

  • Excessive Re-renders : Frequent state updates can lead to a high number of re-renders, especially in components that depend on multiple pieces of state. This can create performance bottlenecks, particularly in large applications with many components.
  • Inefficient Reconciliation : React uses a reconciliation algorithm to determine what changes need to be made to the DOM. When there are too many updates, this process becomes more complex and time-consuming, potentially leading to noticeable delays in UI responsiveness.
  • Increased CPU and Memory Usage : Each re-render consumes CPU resources and memory. If state updates occur rapidly, they can lead to increased load on the browser’s rendering engine, which may cause the application to become sluggish or unresponsive.

Recognizing the challenges posed by traditional state updates, React has evolved to incorporate more efficient rendering techniques, including:

Automatic Batching (React 18+) : React introduced automatic batching, which allows multiple state updates to be batched together, minimizing re-renders. This means that if several state updates occur in the same synchronous event loop (like within an event handler), React groups these updates and performs a single render. This improvement significantly enhances performance, particularly in complex applications.

Advantages of React Batching

  • Reduced Re-renders : Minimizes the number of re-renders by grouping state updates.
  • Improved Performance : Enhances application performance, especially in high-frequency state updates.
  • Smoother User Experience : Provides a more responsive UI by avoiding lag during updates.
  • Less Boilerplate Code : Simplifies code by reducing the need for manual optimization.

The Pre-Batching Era : The Challenges of Traditional State Updates in React

Before React 18 introduced automatic batching for all state updates, React had a form of batching that was limited to native events. This meant that while updates triggered by native browser events (like clicks or keyboard inputs) were batched together to optimize rendering, updates made in asynchronous contexts—such as setTimeout, setInterval, or network requests—were processed individually. Non-browser native events include user-defined events, synthetic events created by React, and any event that occurs outside the direct interaction with the browser interface.

Code Snippet with Native Event Batching

				
					
import React, { useState, useEffect } from 'react';

const NativeEvent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log('Component re-rendered with count:', count);
  }, [count]);

  const handleClick = () => {
    console.log('Before updates, count:', count);
    
    // Batching for native events (handled by React 16)
    setCount((prevCount) => {
      console.log('First update, previous count:', prevCount);
      return prevCount + 1;
    }); // First update

    setCount((prevCount) => {
      console.log('Second update, previous count:', prevCount);
      return prevCount + 1;
    }); // Second update
    
    console.log('After updates in same event loop, count:', count); // Logs initial count (due to batching)
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment with Native Event Batching</button>
    </div>
  );
};

export default NativeEvent;


				
			

Output

Output1_Pre-Batching(Native Event)

What Happens Here

  1. Batching for Native Events : The handleClick function triggers both setCount calls through a native event (the button click).

  2. Single Re-render : React batches these state updates, resulting in a single re-render of the NativeEvent component.

  3. Functional Updates : Using functional updates (prevCount) ensures each update accesses the latest state value for accurate results.

Code Snippet of State Updates Without Batching

Without Batching (Asynchronous Context):

				
					import React, { useState, useEffect } from "react";

const NonNativeUpdate = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component re-rendered with count:", count);
  }, [count]);

  const incrementAsync = () => {
    console.log("Before async updates, count:", count);
    setTimeout(() => {
      // First update (uses functional update to ensure the latest value is used)
      setCount((prevCount) => {
        console.log("First update, previous count:", prevCount);
        return prevCount + 1;
      });
      
      // Second update (again using functional update)
      setCount((prevCount) => {
        console.log("Second update, previous count:", prevCount);
        return prevCount + 1;
      });
    }, 1000);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementAsync}>Increment Async With Two Re-renders</button>
    </div>
  );
};

export default NonNativeUpdate;

				
			

Output

Output2_Pre-Batching(Non-native Event)

What Happens Here

  1. Asynchronous State Updates : In the incrementAsync function, setCount is called within a setTimeout, simulating an asynchronous operation. Since setTimeout is not a native event, React does not automatically batch these updates (before React 18).
  2. Two Distinct Re-renders : With the updated code using functional updates (prevCount => prevCount + 1), each setCount triggers a separate state update and causes two distinct re-renders. This allows users to observe the state change in two steps, which was not possible with direct state updates.
  3. Closure Issue Resolved : By using functional updates, the state inside setTimeout no longer suffers from closure issues. Each setCount call now uses the most recent state value, allowing for consistent and sequential updates. The console.log(‘Count:’, count) inside the timeout still logs the initial value due to closure, but the functional updates ensure the latest state is reflected during rendering.

Post-Batching : Enhancements in State Management and Performance

With the introduction of automatic batching in React 18, all state updates—whether triggered by native events or non-native events—are now batched together. This means that updates made in asynchronous contexts like setTimeout, setInterval, or even inside promises are no longer processed individually. This enhancement reduces unnecessary re-renders and improves performance significantly, especially in applications where multiple updates happen frequently within the same event loop.

Code Snippet with Automatic Batching

				
					import React, { useState, useEffect } from 'react';

const BatchingExample = () => {
  const [count, setCount] = useState(0);
  const [asyncCount, setAsyncCount] = useState(0);
  const [hasRendered, setHasRendered] = useState(false); // Track if it's the first render

  useEffect(() => {
    // Log only on initial render
    if (!hasRendered) {
      console.log('Initial render. Count:', count, 'Async Count:', asyncCount);
      setHasRendered(true);
    } else {
      // Log on subsequent updates
      console.log('Component updated. Count:', count, 'Async Count:', asyncCount);
    }
  }, [count, asyncCount]);

  const handleNativeClick = () => {
    console.log('Before native event batching. Current count:', count);

    // Native event batching - updates are applied immediately
    setCount((prevCount) => {
      console.log('First update for native event, previous count:', prevCount);
      return prevCount + 1;
    });

    setCount((prevCount) => {
      console.log('Second update for native event, previous count:', prevCount);
      return prevCount + 1;
    });
  };

  const handleAsyncClick = () => {
    console.log('Before async updates. Current asyncCount:', asyncCount);

    // Simulating an asynchronous operation
    setTimeout(() => {
      setAsyncCount((prevAsyncCount) => {
        console.log('First update for async, previous asyncCount:', prevAsyncCount);
        return prevAsyncCount + 1;
      });
      setAsyncCount((prevAsyncCount) => {
        console.log('Second update for async, previous asyncCount:', prevAsyncCount);
        return prevAsyncCount + 1;
      });
    }, 1000); // Delay of 1 second before the async updates
  };

  return (
    <div>
      <p>Count (Native Event): {count}</p>
      <p>Async Count (Non-Native Event): {asyncCount}</p>
      <button style={{ margin: '10px' }} onClick={handleNativeClick}>
  Increment Count (Native Event)
</button>
      <button onClick={handleAsyncClick}>Increment Async Count (Non-Native Event)</button>
    </div>
  );
};

export default BatchingExample;
				
			

Output

Output3_Post-Batching

What Happens Now

  1. Native Events (Click)
    When the Increment Count (Native Event) button is clicked, the handleNativeClick function batches the two setCount updates, resulting in a single re-render of the component with the updated count value.

  2. Non-Native Events (Async)
    Clicking the Increment Async Count (Non-Native Event) button triggers the handleAsyncClick function, which sets a timeout for two setAsyncCount updates. These updates are also batched together, leading to one re-render instead of two, optimizing performance by reducing unnecessary updates.

This unified approach to batching state updates makes React’s rendering behavior more consistent and efficient.

The Purpose of flushSync in React Batching

flushSync is needed in batching to force React to apply state updates immediately rather than waiting for the next render cycle. This is particularly useful in scenarios where you want to ensure that the DOM is updated right away after a series of state changes, such as in cases involving animations or when interacting with external libraries that depend on the current state of the DOM. By using flushSync, you can manage complex updates while still benefiting from React’s optimization features.

Code Snippet with flushSync

				
					import React, { useState } from 'react';
import { flushSync } from 'react-dom';

const FlushSyncExample = () => {
  const [counter, setCounter] = useState(0);
  const [flag, setFlag] = useState(false);

   useEffect(() => {
     console.log(counter, flag);
   }, [counter, flag]);

  const handleClick = () => {
    flushSync(() => {
      setCounter(c => c + 1);
    });
    console.log('Counter after first flushSync:', counter); // Logs the updated counter value

    flushSync(() => {
      setFlag(f => !f);
    });
    console.log('Flag after second flushSync:', flag); // Logs the updated flag value
  };

  return (
    <div>
      <p>Counter: {counter}</p>
      <p>Flag: {flag ? 'True' : 'False'}</p>
      <button style={{ margin: '2px' }} onClick={handleClick}>
        Increment Counter and Toggle Flag
      </button>
    </div>
  );
};

export default FlushSyncExample;


				
			

Output

Output4_Post-Batching(flushSync)

What Happens Now with flushSync

Immediate State Updates : When the Increment Counter and Toggle Flag button is clicked, the handleClick function utilizes flushSync for the two state updates. The first flushSync call increments the counter, ensuring that the updated value is immediately available for logging.

Synchronous Rendering : After the first flushSync, the updated counter value is logged, reflecting the immediate change due to flushSync. Following that, the second flushSync toggles the flag. This synchronous update ensures that the new flag state is also logged right away.

Optimized User Experience : By using flushSync, both state updates occur without delay, allowing users to see the updated counter and flag values instantly. This is crucial for maintaining responsiveness in interactive applications, where timely feedback enhances the user experience.

Conclusion

In summary, React’s batching feature enhances performance by consolidating state updates into a single render cycle. This not only minimizes unnecessary re-renders but also streamlines the rendering process, leading to a more responsive user interface. With automatic batching, developers can focus on building applications without worrying about the overhead of manual optimization, making it easier to manage complex state changes efficiently. Overall, mastering batching is essential for creating high-performance React applications.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

March 27, 2024
ReactJS Performance Tuning
July 19, 2024
Simplifying State with Context API
Simplifying State with Context API
August 30, 2024
Simplifying Global State in React with useContext and useReduce
Simplifying Global State in React with useContext and useReducer
Loading...

Featured Projects Portfolios

November 27, 2023
Government Job Platform User-Friendly, Secure and Scalable
Government Job Platform : User-Friendly, Secure, and Scalable
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram