batching

개념

여러 개의 state 업데이트를 하나의 리렌더링 (re-render)로 묶는 것

이유

기존에는 각 state가 변경될 때마다 re-renderning이 발생하여 불필요하게 re-rendering이 많이 발생했다.

function App() {
  const [count, setCount] = useState(0);
  const [active, setActive] = useState(false);

  function handleClick() {
    setCount((c) => c + 1); //Nothing happens
    setActive((f) => !f); //Nothing happens
    //rerender component after this function runs. this is batching.
  }

  return (
    <div>
      <button onClick={handleClick}>{active}</button>
      <h1>{count}</h1>
    </div>
  );
}

React 18 미만, 18 + ReactDOM.render()

React 이벤트 핸드러 내부에서 발생하는 업데이트만 배칭이 가능.
그 외 Promise, setTimeout, Native event handler에서는 배칭이 되지 않는다.

setTimeout(() => {
  setCount((c) => c + 1); //rerender
  setActive((f) => !f); //rerender
}, 1000)

React 18

React 18 + createRoot로 Automatic batching이 가능하다.
Automatic batching이란 React는 업데이트의 발생지점과 무관하게 자동으로 업데이트를 배칭하는 것

이전버전에서 안됐던 상황에서도 가능하다는 뜻이다.

setTimeout

setTimeout(() => {
  setCount((c) => c + 1); //Nothing happens
  setActive((f) => !f); //Nothing happens
  //rerender component after this function runs. this is batching.
}, 1000)

fetch

fetch().then(() => {
  setCount((c) => c + 1); //Nothing happens
  setActive((f) => !f); //Nothing happens
  // rerender component after this function runs. this is batching.
})

Native event handler

btn.addEventListener('click', () => {
  setCount((c) => c + 1); //Nothing happens
  setActive((f) => !f); //Nothing happens
 //rerender component after this function runs. this is batching.
})