ReasonJun

React 18 : Automatic batching 본문

Frontend/React

React 18 : Automatic batching

ReasonJun 2023. 6. 16. 01:53
728x90

Automatic batching is a feature introduced in React 18 that simplifies the process of batching multiple state updates together, reducing unnecessary re-renders and improving performance in React applications.

 

In earlier versions of React, when multiple setState calls were made consecutively within the same event handler or lifecycle method, each state update triggered a separate re-render of the component. This behavior could lead to suboptimal performance when multiple state updates occurred in quick succession, as each update triggered a separate render cycle.

 

With automatic batching in React 18, state updates are automatically batched together, ensuring that multiple setState calls within the same event loop are treated as a single update. This means that the component will only re-render once, after all the state updates have been processed.

 

Automatic batching applies not only to setState calls within component event handlers but also to other React APIs that trigger re-renders, such as useState, useReducer, and custom hooks.

 

Here's an example to illustrate how automatic batching works:

function ExampleComponent() {
  const [count, setCount] = useState(0);

  function handleButtonClick() {
    setCount(count + 1);  // First state update
    setCount(count + 1);  // Second state update
  }

  console.log(count); // Output: 0 (before batched updates)

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleButtonClick}>Increment</button>
    </div>
  );
}

In this example, when the button is clicked, the handleButtonClick function is executed. It calls setCount twice, incrementing the count by 1 in each call. In previous versions of React, this would have resulted in two separate re-renders of the component. However, with automatic batching in React 18, the state updates are batched together, and the component only re-renders once, resulting in an updated count of 2.

 

 

https://velog.io/@rookieand/React-18%EC%97%90%EC%84%9C-%EC%B6%94%EA%B0%80%EB%90%9C-Auto-Batching-%EC%9D%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80

 

React 18에서 추가된 Auto Batching 은 무엇인가?

setState를 많이 실행시켜도 리렌더링이 한번만 일어나는 이유는 무엇인가?

velog.io

 

728x90

'Frontend > React' 카테고리의 다른 글

React 18 : Transition  (0) 2023.06.16
React 18 : Suspense  (0) 2023.06.16
React: useRef  (0) 2023.06.14
React : debounce  (0) 2023.06.14
React : Request AJAX within the component (two way)  (0) 2023.06.14
Comments