React 18 - Automatic batching
Created by Qiwei on 6/24/2021
以下是英文原文的翻译
React 18 添加了开箱即用的性能提升,默认做了更多的批处理,不再需要在应用程序或库代码中手动进行批处理更新。这篇文章将解释什么是批处理,它以前是如何工作的,以及有什么变化。
这是一个深入的功能,我们并不期望大多数用户需要考虑这个问题。然而,它可能与教育者和库开发者有关。
什么是批处理?
批处理(Batching)是指 React 将多个状态更新合并到单个重新渲染中以获得更好的性能。
例如,如果你在同一个点击事件里有两个状态更新,React 总是把它们批处理到一个重新渲染中。如果你运行下面的代码,你会看到每次点击时,React 只执行一次渲染,尽管你设置了两次状态:
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
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!)
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}- ✅ Demo: React 17 batches inside event handlers.(注意一次点击只有一次渲染)
这对性能来说是很好的,因为它避免了不必要的重新渲染。它还可以防止你的组件呈现“半成品”状态,即只有一个状态变量被更新。这可能会让你想起,当你选择第一道菜时,餐厅的服务员不会跑到厨房,而是等待你完成你的订单。
然而,React 对它何时批量更新并不一致。例如,如果你需要获取数据,然后在上面的 handleClick 中更新状态,那么 React 就不会批量更新,而是执行两个独立的更新。
这是因为 React 过去只在浏览器事件(如点击)期间进行批处理更新,但在这里我们是在事件已经被处理后(在 fetch callback)才更新状态:
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
// React 17 and earlier does NOT batch these because
// they run *after* the event in a callback, not *during* it
setCount(c => c + 1); // Causes a re-render
setFlag(f => !f); // Causes a re-render
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}
- 🟡 Demo: React 17 does NOT batch outside event handlers.(注意一次点击有两次渲染)
在 React 18 之前,我们只在 React 事件处理 handler 中批量更新。默认情况下,在 React 中,Promise、setTimeout、本地事件 handler 或任何其他事件中的更新是不会批处理的。
什么是自动批处理?
从 React 18 的 createRoot 开始,所有的更新都会被自动,无论它们来自哪里。
这意味着超时、Promise、本地事件 handler 或任何其他事件中的更新,将以与 React 事件中的更新相同的方式进行批处理。我们希望这将导致更少的渲染工作,从而提高应用程序的性能:
function App() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
function handleClick() {
fetchSomething().then(() => {
// React 18 and later DOES batch these:
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
});
}
return (
<div>
<button onClick={handleClick}>Next</button>
<h1 style={{ color: flag ? "blue" : "black" }}>{count}</h1>
</div>
);
}- ✅ Demo: React 18 with createRoot batches even outside event handlers! (注意一次点击只有一次渲染)
- 🟡 Demo: React 18 with legacy render keeps the old behavior (注意一次点击有两次渲染)
注意:我们期望你在采用 React 18 时会升级到
creatRoot。渲染的旧行为的存在只是为了更容易在生产中对两个版本进行实验。
React 会自动批量更新,无论更新发生在哪里,所以:
function handleClick() {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
}行为与下面的几段代码一致:
setTimeout(() => {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
}, 1000);fetch(/*...*/).then(() => {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
})elm.addEventListener('click', () => {
setCount(c => c + 1);
setFlag(f => !f);
// React will only re-render once at the end (that's batching!)
});注意:React 只在比较安全的情况下进行批量更新。比如 React 确保每个用户发起的事件,如点击或按键事件,DOM 会在下一个事件之前被完全更新。这可以确保一个在提交时被禁用的表单不会被提交两次。
如果我不想要批处理怎么办?
通常情况下批处理是安全的,但有些代码可能依赖于在状态改变后立即从 DOM 中读取一些东西。对于这些用例,你可以使用 ReactDOM.flushSync() 来选择不进行批处理。
import { flushSync } from 'react-dom'; // Note: react-dom, not react
function handleClick() {
flushSync(() => {
setCounter(c => c + 1);
});
// React has updated the DOM by now
flushSync(() => {
setFlag(f => !f);
});
// React has updated the DOM by now
}