동일한 클릭 이벤트 내에 두 개의 상태 업데이트가 있는 경우, 클릭할 때마다 하나의 리-렌더링으로
일괄 처리하는 걸 알 수 있다.
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
setCount(c => c + 1);
setFlag(f => !f);
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}
React의 Batching 처리에 대한 큰 변화는
React 18 version
이전과 이후라고 말할 수 있다.
handleClick
은 업데이트를 일괄 처리 하지 않고 두 개의 독립적인 업데이트를 수행하는 걸 알 수 있다.function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
setCount(cnt => cnt + 1); // 리-렌더링 발생
setFlag(f => !f); // 리-렌더링 발생
});
}
console.log("re-rendering 발생")
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
setCount(cnt => cnt + 1);
setFlag(f => !f);
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}
flushSync()
를 사용할 수 있습니다.import { flushSync } from 'react-dom';
function handleClick() {
flushSync(() => {
setCounter(cnt => cnt + 1);
});
flushSync(() => {
setFlag(f => !f);
});
}