nmsn / blog

记录日常遇到的问题,需要记录的笔记以及新学到的知识,会进行汇总和分类,自动更新 README,欢迎评论和补充,互相学习
37 stars 0 forks source link

React18批处理 #5

Open nmsn opened 2 years ago

nmsn commented 2 years ago

https://github.com/reactwg/react-18/discussions/21

nmsn commented 2 years ago

在 React 18之前,我们只在反应事件处理过程中批量更新。在 React 默认情况下,promises、 setTimeout、本机事件处理程序或任何其他事件中的更新都不会批处理。

从 18 开始,所有的更新都会自动批处理,不管它们来自哪里。

无论更新发生在哪里,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);
behaves the same as this:

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!)
});

有相同的表现形式。