HardReact Fundamentals📖 Theory Question

Understanding React 18's Automatic Batching

💡

Hint

Consider how React's state update handling has changed between versions 17 and 18, specifically how re-renders are triggered

Full Answer

React 18 introduced a new feature called Automatic Batching, which automatically batches multiple state updates into a single re-render. This feature improves the performance of React applications by reducing the number of re-renders.

import { useState } from 'react'; function Counter() {   const [count, setCount] = useState(0);   function handleClick() {     setCount(count + 1);     setCount(count + 1);   }   return (     

Count: {count}

); }

In React 17 and earlier, the above code would cause the component to re-render twice. However, with React 18's Automatic Batching, the two state updates are batched into a single re-render.

Key differences: The key difference between React 17 and React 18 is how they handle state updates. In React 17, each state update triggers a re-render, whereas in React 18, multiple state updates are batched into a single re-render.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint