[React] React 18, Automatic batching

Narcoker·2023년 7월 3일
0

React

목록 보기
20/32

Automatic batching

batching 은 업데이트 대상이 되는 상태값들을 하나의 그룹으로 묶어서
한번의 리렌더링 업데이트가 진행될 수 있는 것을 의미한다.

즉, 하나의 함수 안에서 setState를 아무리 많이 호출시키더라도
리렌더링은 한번만 발생한다.

// 렌더링 한번만 발생
function handleClick() {
	setCount(c => c + 1); // Does not re-render yet 
	setFlag(f => f!);  // Does not re-render yet
	// React will only re-render once at the end(that's batching!)
}

이 기능은 여러번 리렌더링하는 것을 막기때문에 성능상 좋다.

18버전 이전에서도 Automatic batching은 지원했다.
하지만 api 호출에 콜백으로 넣은 함수나 timeouts 함수에서는 작동하지 않았다.

function handleClick() {
	fetchSomething().then(()=> {
    	// React 17 and earliear dos Not batch these because
        // they run "after" the event in a callback, not "during" it
		setCount(c => c + 1); // re-render 
		setFlag(f => f!);  // re-render
    });
}

setTimeout(()=>{
	setCount(c => c + 1); // re-render occurs
    setFlag(f => !f); // re-render occurs again!
}, 1000);

batch 처리를 의도적으로 막는 방법

ReactDOM.flushSync()를 사용하여 일괄 처리를 막을 수 있다.

import { flushSync } from "react-dom";

function handleClick() {
	flushSync(()=> {
    	setCount(count+1);
    }); // re-render

 	flushSync(()=> {
    	setCount(true);
    }); // re-render
profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글