React 18 发布

React 18 现已发布,此版本包括开箱即用的改进,如自动批处理,新的 API(如 startTransition)和支持 Suspense 的流式服务器端渲染。

公告指出,React 18 中的许多功能都建立在新的并发渲染器之上,这是一个解锁强大新功能的更改。Concurrent React 是可选的,它仅在用户使用并发功能时启用,但开发团队认为它将会对大众构建应用程序的方式产生重大影响。

我们花了数年时间研究和开发对 React 并发的支持,并且我们特别注意为现有用户提供逐步采用的路径。去年夏天,我们成立了 React 18 工作组,收集社区专家的反馈,确保整个 React 生态系统的顺利升级体验。

React 18 的新功能如下:

  • 自动批处理。批处理是 React 将多个状态更新分组到一个重新渲染中以获得更好的性能。如果没有自动批处理,我们只能在 React 事件处理程序中批处理更新。默认情况下,Promise、setTimeout、native event handlers 或任何其他事件内部的更新不会在 React 中批处理。使用自动批处理,这些更新将自动批处理:
// Before: only React events were batched.
setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React will render twice, once for each state update (no batching)
}, 1000);

// After: updates inside of timeouts, promises,
// native event handlers or any other event are batched.`
setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React will only re-render once at the end (that's batching!)
}, 1000);
  • Transitions 是 React 中的一个新概念,用于区分 urgent 和 non-urgent updates。
    • Urgent updates 反映了直接交互,例如 typing、clicking、pressing等。
    • Transition updates 将 UI 从一个视图转换到另一个视图。
import {startTransition} from 'react';

// Urgent: Show what was typed
setInputValue(input);

// Mark any state updates inside as transitions
startTransition(() => {
  // Transition: Show the results
  setSearchQuery(input);
});
  • 新的 Suspense 功能。如果组件树的一部分尚未准备好显示,Suspense 允许你以声明方式指定组件树的加载状态:

<Suspense fallback={<Spinner />}>
  <Comments />
</Suspense>

Suspense 使“UI loading state”成为 React 编程模型中的 first-class 声明性概念。这让我们可以在它之上构建更高级别的功能。

React 18 中在服务器上添加了对 Suspense 的支持,并使用并发渲染特性扩展了它的功能。React 18 中的 Suspense 与 transition API 结合使用时效果最佳。如果你在 transition 期间 suspend,React 将防止已经可见的内容被 fallback 所取代。相反,React 会延迟渲染,直到加载了足够的数据以防止出现错误的加载状态。

  • 新的客户端和服务器渲染 API。这些更改允许用户在升级到 React 18 中的新 API 时继续使用 React 17 模式下的旧 API。
  • 新的严格模式行为 (Strict Mode Behaviors)。此功能将为 React 应用程序提供更好的开箱即用性能,但要求组件能够对多次挂载和销毁的效果具有弹性。大多数效果无需任何更改即可工作,但有些效果假定它们只挂载或销毁一次。为了帮助解决这些问题,React 18 为严格模式引入了一个新的仅限开发的检查。每当第一次安装组件时,此新检查将自动卸载并重新挂载每个组件,并在第二次挂载时恢复先前的状态。​​​​​
* React mounts the component.
  * Layout effects are created.
  * Effects are created.
* React simulates unmounting the component.
  * Layout effects are destroyed.
  * Effects are destroyed.
* React simulates mounting the component with the previous state.
  * Layout effects are created.
  * Effects are created.

更多详情可查看:https://reactjs.org/blog/2022/03/29/react-v18.html

猜你喜欢

转载自www.oschina.net/news/188872/reactjs-18-released