{"id":66022,"date":"2024-09-23T10:51:39","date_gmt":"2024-09-23T05:21:39","guid":{"rendered":"https:\/\/www.tothenew.com\/blog\/?p=66022"},"modified":"2024-09-23T11:31:12","modified_gmt":"2024-09-23T06:01:12","slug":"understanding-state-batching-in-react","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/understanding-state-batching-in-react\/","title":{"rendered":"Understanding State Batching in React"},"content":{"rendered":"<h3>Introduction<\/h3>\n<p>In the world of React, efficient rendering and performance optimization are the keys to success. One of the most important concepts that plays a key role in React state updates is <strong>State Batching\/Automatic Batching<\/strong>. This mechanism was introduced in <a href=\"https:\/\/react.dev\/blog\/2022\/03\/29\/react-v18\"><strong>React version 18<\/strong><\/a>, which significantly impacts the application&#8217;s performance and management of the state updates. In this blog, we\u2019ll dive deep into the concept and break down all the mysteries of state batching, why it is important, and how we can manage it effectively in our<strong> <a href=\"https:\/\/www.tothenew.com\/react-native-development-services\">React applications<\/a><\/strong>.<\/p>\n<h3>What is State Batching?<\/h3>\n<p>When we set a state variable in React, it triggers a <strong><a href=\"https:\/\/react.dev\/learn\/render-and-commit#re-renders-when-state-updates\">re-render<\/a><\/strong>. However, there are times when we might want to perform several operations on the state value before initiating the next render. To manage this effectively, we play by the rules of the state batching mechanism. <strong>State batching<\/strong> is a performance optimization technique used by React to minimize the number of re-renders and improve the efficiency of updates. Instead of processing each state update immediately, React groups multiple state updates and processes them in a single render. This ensures that components are only re-rendered once, regardless of how many state updates are triggered.<\/p>\n<p>Let&#8217;s break down state batching in the simplest terms:<\/p>\n<div id=\"attachment_66223\" style=\"width: 310px\" class=\"wp-caption aligncenter\"><img aria-describedby=\"caption-attachment-66223\" decoding=\"async\" loading=\"lazy\" class=\"size-medium wp-image-66223\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2024\/09\/state-300x251.png\" alt=\"state batching\" width=\"300\" height=\"251\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2024\/09\/state-300x251.png 300w, \/blog\/wp-ttn-blog\/uploads\/2024\/09\/state.png 408w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><p id=\"caption-attachment-66223\" class=\"wp-caption-text\">The Dinner Party Analogy<\/p><\/div>\n<h5>Imagine you\u2019re hosting a dinner party and you have a rule that you\u2019ll only serve food when you have a full tray.<\/h5>\n<p><strong>Without Batching<\/strong>: Every time someone asks for a drink or a snack, you immediately go to the kitchen and bring it out, even if it\u2019s just one item. So, you\u2019re making many trips back and forth to the kitchen.<br \/>\n<strong>With Batching<\/strong>: Instead, you wait until several guests have requested different items. Once you have a full tray of requests, you go to the kitchen, fill the tray, and serve everything in one trip. This way, you make fewer trips and get everything delivered faster and more efficiently.<\/p>\n<h4><!--more--><strong>Also Read<\/strong>:<a href=\"https:\/\/www.tothenew.com\/blog\/powering-dynamic-web-apps-integrating-react-with-drupal-10-api-for-security-and-efficiency\/\"> Powering Dynamic Web Apps: Integrating React with Drupal 10 API for Security and Efficiency<\/a><\/h4>\n<p>Now let&#8217;s try to understand how this works using code:<\/p>\n<pre>import { useState } from 'react';\r\n\r\nexport default function Counter() {\r\n    const [count, setCount] = useState(0);\r\n    const handleClick = () =&gt; {\r\n       setCount(count + 1);\r\n       setCount(count + 1);\r\n       setCount(count + 1);\r\n       setCount(count + 1);\r\n       setCount(count + 1);\r\n    };\r\n    return (\r\n        &lt;&gt;\r\n          &lt;h1&gt;{count}&lt;\/h1&gt; \r\n          &lt;button onClick={handleClick}&gt;+5&lt;\/button&gt;\r\n        &lt;\/&gt;\r\n    );\r\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div id=\"attachment_66023\" style=\"width: 329px\" class=\"wp-caption alignleft\"><img aria-describedby=\"caption-attachment-66023\" decoding=\"async\" loading=\"lazy\" class=\"wp-image-66023\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2024\/09\/batching-1-300x77.png\" alt=\" batching image\" width=\"319\" height=\"82\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2024\/09\/batching-1-300x77.png 300w, \/blog\/wp-ttn-blog\/uploads\/2024\/09\/batching-1.png 519w\" sizes=\"(max-width: 319px) 100vw, 319px\" \/><p id=\"caption-attachment-66023\" class=\"wp-caption-text\">This image represents the initial render of the react application having an initial value of count (i.e. 0) and a button +5 render of the react application.<\/p><\/div>\n<div id=\"attachment_66020\" style=\"width: 357px\" class=\"wp-caption alignleft\"><img aria-describedby=\"caption-attachment-66020\" decoding=\"async\" loading=\"lazy\" class=\" wp-image-66020\" src=\"https:\/\/www.tothenew.com\/blog\/wp-ttn-blog\/uploads\/2024\/09\/batching-2-300x70.png\" alt=\"batching image\" width=\"347\" height=\"81\" srcset=\"\/blog\/wp-ttn-blog\/uploads\/2024\/09\/batching-2-300x70.png 300w, \/blog\/wp-ttn-blog\/uploads\/2024\/09\/batching-2.png 525w\" sizes=\"(max-width: 347px) 100vw, 347px\" \/><p id=\"caption-attachment-66020\" class=\"wp-caption-text\">This image represents the incremented count value (i.e. 1) after clicking on the +5 button.<\/p><\/div>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h5><strong>Explanation:<\/strong><\/h5>\n<ul>\n<li>According to the first look of the above code, as we click on the &#8216;+5&#8217; button, it is expected to display &#8216;5&#8217; as the output, due to <strong>setCount (count +1)<\/strong> being called 5 times in a row causing it to re-render 5 times. However, as the second image represents, it displays the count state as &#8216;1&#8217; when the button is clicked.<\/li>\n<li>According to React, <a href=\"https:\/\/react.dev\/learn\/state-as-a-snapshot#rendering-takes-a-snapshot-in-time\"><strong>every state value being rendered is<\/strong> <strong>fixed<\/strong><\/a>. Therefore, the value of the state (count) inside the first render&#8217;s event handler is always 0. No matter how often it has been triggered, React will wait until all code in the event handlers has run before processing the state updates.<\/li>\n<li>This is why the re-render only happens after all the <strong>setCount()<\/strong> are called. This prevents us from re-rendering as we update multiple states being called from the same or different components without triggering re-renders. This concept is known as Batching where the React waits until all code in the event handlers has run and then starts updating the UI. This process helps React applications to run faster.<\/li>\n<\/ul>\n<h3><strong>Why State Batching is important?<\/strong><\/h3>\n<ul>\n<li><strong>Performance Optimization<\/strong>: By batching state updates, React reduces the number of re-renders and therefore the amount of work needed to update the DOM is decreased which leads to smoother and more efficient applications.<\/li>\n<li><strong>Predictable Behavior<\/strong>: With state batching, state updates are predictable and less prone to causing race conditions or unexpected behaviors as React processes all state updates in a controlled manner.<\/li>\n<\/ul>\n<h3>Updating the same state multiple times before the next render<\/h3>\n<p>There can be an uncommon scenario where we would like to update the same state variable multiple times before the next render happens. To handle this kind of case, instead of passing the next state like <strong>setCount(count+1)<\/strong>, we can pass a function that calculates the next state based on the previous one, like <strong>setCount(prevCount =&gt; prevCount + 1)<\/strong>. Using this method we are telling React to remember the previous state and perform the task, instead of replacing it.<\/p>\n<p>So, if we replace <strong>setCount(count+1)<\/strong> to <strong>setCount(prevCount =&gt; prevCount + 1)<\/strong> then <strong>prevCount =&gt; prevCount =&gt; prevCount + 1<\/strong> will act as an updater function which will queue the previous value for further tasks.<\/p>\n<table style=\"border-collapse: collapse; width: 43.5007%; height: 201px;\">\n<tbody>\n<tr style=\"height: 23px;\">\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\"><strong>Queued Update<\/strong><\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\"><strong>prevCount<\/strong><\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\"><strong>returns<\/strong><\/td>\n<\/tr>\n<tr style=\"height: 23px;\">\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">prevCount + 1<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">0<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">0 + 1 = 1<\/td>\n<\/tr>\n<tr style=\"height: 23px;\">\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">prevCount + 1<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">1<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">1 + 1 = 2<\/td>\n<\/tr>\n<tr style=\"height: 23px;\">\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">prevCount + 1<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">2<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">2 + 1 = 3<\/td>\n<\/tr>\n<tr style=\"height: 23px;\">\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">prevCount + 1<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">3<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">3 + 1 = 4<\/td>\n<\/tr>\n<tr style=\"height: 23px;\">\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">prevCount + 1<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">4<\/td>\n<td style=\"width: 33.3333%; height: 23px; text-align: center;\">\u00a04 + 1 = 5<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>So, when we call the updater function, it gets added to a queue. When React calls <strong><a href=\"https:\/\/react.dev\/reference\/react\/useState\">useState<\/a><\/strong> for the next render, it goes through the queue. In our case, the initial value of &#8220;count&#8221; (i.e. 0) will be passed as an argument to prevCount in the updater function. React takes the returned value of our previous updater function and passes it to the next updater as prevCount and so on, storing &#8216;5&#8217; as the final result. That is how we can update the state using the previous state value.<\/p>\n<h3>Conclusion<\/h3>\n<p>State Batching is a crucial optimization in React, that enhances performance and consistency by grouping multiple state updates into a single render pass. Understanding how State Batching works can help one write more efficient and predictable React applications. By leveraging State Batching effectively and keeping up with React\u2019s advancements, we can build smoother and more responsive user interfaces that provide a better experience for all users. Get a free consultation on how we can help with <a href=\"https:\/\/www.tothenew.com\/digital-engineering\/web-development\">Web Development services<\/a>. <a href=\"https:\/\/www.tothenew.com\/contact-us\">Click here<\/a> to schedule a meeting with us.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In the world of React, efficient rendering and performance optimization are the keys to success. One of the most important concepts that plays a key role in React state updates is State Batching\/Automatic Batching. This mechanism was introduced in React version 18, which significantly impacts the application&#8217;s performance and management of the state updates. [&hellip;]<\/p>\n","protected":false},"author":1948,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":49},"categories":[5876],"tags":[6516,4064],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/66022"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1948"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=66022"}],"version-history":[{"count":12,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/66022\/revisions"}],"predecessor-version":[{"id":67218,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/66022\/revisions\/67218"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=66022"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=66022"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=66022"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}