对react 18 官方文章,做一个浅显的翻译和理解。

最近在使用 react 18,也看过一遍官方文档,但由于英文阅读能力有限,每次都是比较耗时,所以想讲自己的理解写在这里,方便自己快速查看学习。(直接搬用官方文档,不知道算不算侵权,如有问题,请评论留言)

React 18 官方文档

In our last post, we shared step-by-step instructions for upgrading your app to React 18. In this post, we’ll give an overview of what’s new in React 18, and what it means for the future.

在上一章节中,我们一步步介绍了《更新应用到react 18》。在这一个章节中,我们给出 react 18 新内容的概述,以及这些新内容将来有什么意义。

Our latest major version includes out-of-the-box improvements like automatic batching, new APIs like startTransition, and streaming server-side rendering with support for Suspense.

我们最新的大版本中包含开箱即用的能力,比如自动批处理,新的 API(比如 startTransition),和支持 Suspense 的流服务端渲染。(可以参考构建Streaming SSR应用可行性调研

Many of the features in React 18 are built on top of our new concurrent renderer, a behind-the-scenes change that unlocks powerful new capabilities. Concurrent React is opt-in — it’s only enabled when you use a concurrent feature — but we think it will have a big impact on the way people build applications.

react 18 的许多特性是基于我们新的并发渲染,一个后台的改变,可以解锁强大的新能力。Concurrent React 是可选择的——它仅仅在你使用一个并发功能时启用——但是我们认为它将对人们搭建应用的方式产生重大的影响力。

We’ve spent years researching and developing support for concurrency in React, and we’ve taken extra care to provide a gradual adoption path for existing users. Last summer, we formed the React 18 Working Group to gather feedback from experts in the community and ensure a smooth upgrade experience for the entire React ecosystem.

我们花费数年研究和开发支持 React 并发,同时我们也额外关注为已有用户提供一种逐渐升级的方式。去年夏天,我们成立了 React 18 工作小组 收集来自社区专家的反馈,确保整个 react 生态系统的顺利升级体验。

In case you missed it, we shared a lot of this vision at React Conf 2021:

以防你错过,我们在 React Conf 2021 分享了大量这样的构想:

  • 在 the keynote,我们解释了 React 18 是如何融入到任务中,让开发人员更轻松地构建更好的用户体验。
  • Shruti Kapoor 演示了如何使用 react 18 的新特性。
  • Shaundai Person 给我们概述了 Suspense 的流服务端渲染。

Below is a full overview of what to expect in this release, starting with Concurrent Rendering.

接下来全面概述这个版本所期望的内容,从 Concurrent Rendering 开始。

Note for React Native users: React 18 will ship in React Native with the New React Native Architecture. For more information, see the React Conf keynote here.


What is Concurrent React?

The most important addition in React 18 is something we hope you never have to think about: concurrency. We think this is largely true for application developers, though the story may be a bit more complicated for library maintainers.

React 18里最重要的新增内容就是并发,我们希望你从没想过这件事情。我们认为这对于应用开发人员来说基本是正确的,尽管这个事情对于库维护人员来说可能更加复杂。

Concurrency is not a feature, per se. It’s a new behind-the-scenes mechanism that enables React to prepare multiple versions of your UI at the same time. You can think of concurrency as an implementation detail — it’s valuable because of the features that it unlocks. React uses sophisticated techniques in its internal implementation, like priority queues and multiple buffering. But you won’t see those concepts anywhere in our public APIs.

Concurrency 不是一个特性。它是一个新的后台机制,允许 react 同时准备多个 UI 版本。你可以把并发想象成一个实现细节——它的价值在于它所解锁的特性。React 在其内部的执行中使用复杂的技术,比如优先级队列和多缓冲。但是你不会在公共API中看到有关这些的任何方面。

When we design APIs, we try to hide implementation details from developers. As a React developer, you focus on what you want the user experience to look like, and React handles how to deliver that experience. So we don’t expect React developers to know how concurrency works under the hood.

当我们设计API时,我们会尽量对开发人员隐藏实现细节。作为一名 React 开发人员,你关注于你想要用户体验是什么,以及 React 处理如何达到这个体验。所以我们不指望 React 开发人员了解并发性是如何工作的。

However, Concurrent React is more important than a typical implementation detail — it’s a foundational update to React’s core rendering model. So while it’s not super important to know how concurrency works, it may be worth knowing what it is at a high level.

然而,Concurrent React 比典型的实现细节更加重要——它是 React 的核心渲染模型的基础更新。所以尽管了解如何并发性工作并没有那么重要去,但是或许值得知道在高层次上它是什么。

A key property of Concurrent React is that rendering is interruptible. When you first upgrade to React 18, before adding any concurrent features, updates are rendered the same as in previous versions of React — in a single, uninterrupted, synchronous transaction. With synchronous rendering, once an update starts rendering, nothing can interrupt it until the user can see the result on screen.

Concurrent React 的一个关键属性是渲染可中断。当你第一次升级 React 18,在添加任一并发特性之前,渲染的更新和 React 之前的版本一样——在一个单线程,不可中断,同步的事务中。在同步渲染下,一旦更新开始渲染,就不可能中断,直到用户在屏幕上看到渲染结果。

In a concurrent render, this is not always the case. React may start rendering an update, pause in the middle, then continue later. It may even abandon an in-progress render altogether. React guarantees that the UI will appear consistent even if a render is interrupted. To do this, it waits to perform DOM mutations until the end, once the entire tree has been evaluated. With this capability, React can prepare new screens in the background without blocking the main thread. This means the UI can respond immediately to user input even if it’s in the middle of a large rendering task, creating a fluid user experience.

对于异步渲染,这并不是常见的情况。React 可能开始渲染更新,中间暂停,稍后再继续。它甚至可能放弃在进程中的渲染。React 保证即使渲染被中断 UI 呈现不变。为了实现这个,需要等到结束后执行 DOM 的变化,也就是评估完整个树的变化。使用这个能力,React 可以在不阻塞主要线程的情况下,在后台准备新的屏幕。这意味着 UI 可以立即响应给到用户输入,创造流畅的用户体验,即使是在一次大的渲染任务里。

Another example is reusable state. Concurrent React can remove sections of the UI from the screen, then add them back later while reusing the previous state. For example, when a user tabs away from a screen and back, React should be able to restore the previous screen in the same state it was in before. In an upcoming minor, we’re planning to add a new component called <Offscreen> that implements this pattern. Similarly, you’ll be able to use Offscreen to prepare new UI in the background so that it’s ready before the user reveals it.

另一个例子是可重用状态。Concurrent React 可以从屏幕中移除 UI 的部分,然后在重用前一个状态时再添加回来。例如,用户 tab 切换离开屏幕并返回时,React 应该能够将前一个屏幕恢复到与之前相同的状态下。在即将到来的次要版本中,我们计划增加一个<Offscreen>新组件来实现这个模式。同样地,你也可以用 Offscreen 在后台准备一个新的 UI,在用户展示它之前准备好。

Concurrent rendering is a powerful new tool in React and most of our new features are built to take advantage of it, including Suspense, transitions, and streaming server rendering. But React 18 is just the beginning of what we aim to build on this new foundation.

并发渲染是 React 里强大的新工具,并且我们大部分新特性都是利用它去搭建的,包括 Suspense,过渡,和流服务端渲染。但是 React 18 仅仅是我们在这个新基础上的目标的开始。


Gradually Adopting Concurrent Features

Technically, concurrent rendering is a breaking change. Because concurrent rendering is interruptible, components behave slightly differently when it is enabled.

严格来说,并发渲染是一个破坏性改变。因为并发渲染是可中断的,当启用时,组件行为会有细微的不同。

In our testing, we’ve upgraded thousands of components to React 18. What we’ve found is that nearly all existing components “just work” with concurrent rendering, without any changes. However, some of them may require some additional migration effort. Although the changes are usually small, you’ll still have the ability to make them at your own pace. The new rendering behavior in React 18 is only enabled in the parts of your app that use new features.

在我们的测试中,我们已经数千个组件升级到 React 18 。我们发现几乎所有存在的组件在并发渲染下“正常工作”,而没有任何变化。然而,有一些组件可能需要额外的迁移工作。尽管这些变化通常很小,但是你仍然有能力让它们在你的掌控中。React 18 新的渲染行为仅仅在应用中使用新特性的部分启用。

The overall upgrade strategy is to get your application running on React 18 without breaking existing code. Then you can gradually start adding concurrent features at your own pace. You can use <StrictMode> to help surface concurrency-related bugs during development. Strict Mode doesn’t affect production behavior, but during development it will log extra warnings and double-invoke functions that are expected to be idempotent. It won’t catch everything, but it’s effective at preventing the most common types of mistakes.

整体的更新策略是在不破坏已有代码的情况下,能在React 18 运行你的应用。然后你可以按照自己的节奏开始逐渐添加并发特性。你可以在开发过程中使用<StrictMode>来帮助显示并发相关的bug。Strict Mode 不影响正式环境行为,但在开发环境,将会记录额外的警告和双重调用函数,这些函数应该是幂等的。它不会捕获所有的事情,但是可以有效防止最常见的错误。

After you upgrade to React 18, you’ll be able to start using concurrent features immediately. For example, you can use startTransition to navigate between screens without blocking user input. Or useDeferredValue to throttle expensive re-renders.

升级 React 18 后,你可以立即开始使用并发特性。例如,你可以使用 startTransition 在多个屏幕之间导航,而不阻塞用户输入。或者 useDeferredValue 来抑制昂贵的重绘。

However, long term, we expect the main way you’ll add concurrency to your app is by using a concurrent-enabled library or framework. In most cases, you won’t interact with concurrent APIs directly. For example, instead of developers calling startTransition whenever they navigate to a new screen, router libraries will automatically wrap navigations in startTransition.

然而,从长期来说,我们期望在应用中添加并发性的主要方式是通过使用并发启用的库或者框架。在大部分情况,你不会直接与并发 API 发生交互。例如,与开发者导航到新的屏幕时调用 startTransition 不同,路由库将在 startTransition 自动包装导航。

It may take some time for libraries to upgrade to be concurrent compatible. We’ve provided new APIs to make it easier for libraries to take advantage of concurrent features. In the meantime, please be patient with maintainers as we work to gradually migrate the React ecosystem.

依赖库升级到并发兼容需要一些时间。我们提供了新的 API, 让依赖库更容易地利用并发特性。同时,请耐心等候,我们维护人员正逐步迁移 React 生态系统。


Suspense in Data Frameworks

In React 18, you can start using Suspense for data fetching in opinionated frameworks like Relay, Next.js, Hydrogen, or Remix. Ad hoc data fetching with Suspense is technically possible, but still not recommended as a general strategy.

React 18,你可以在特定的框架里开始使用 Suspense 获取数据,比如Relay, Next.js, Hydrogen, 或者 Remix等框架。用 Suspense 获取特定数据在技术上是可行的,但是仍然不推荐作为一般策略。

In the future, we may expose additional primitives that could make it easier to access your data with Suspense, perhaps without the use of an opinionated framework. However, Suspense works best when it’s deeply integrated into your application’s architecture: your router, your data layer, and your server rendering environment. So even long term, we expect that libraries and frameworks will play a crucial role in the React ecosystem.

未来,我们可能抛出另外的接口,可以用 Suspense 更容易地访问数据,或许不用使用特定的框架。然而,Suspense 在深度集成到应用结构(路由、数据层、和服务端渲染环境)时效果最好。所以从长期来看,我们期望库和框架在 React 生态系统中扮演重要的角色。

As in previous versions of React, you can also use Suspense for code splitting on the client with React.lazy. But our vision for Suspense has always been about much more than loading code — the goal is to extend support for Suspense so that eventually, the same declarative Suspense fallback can handle any asynchronous operation (loading code, data, images, etc).

在 React 以前的版本,你也可以使用 Suspense 在客户端通过 React.lazy 做代码分割。但是我们对 Suspense 的构想远不止于加载代码——我们的目标是扩展对 Suspense 的支持,最终,同样的声明 Suspense 回退可以处理任何异步操作(加载代码、数据、图片等)。


Server Components is Still in Development

Server Components is an upcoming feature that allows developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering. Server Components is not inherently coupled to Concurrent React, but it’s designed to work best with concurrent features like Suspense and streaming server rendering.

Server Components 是即将到来的特性,它允许开发者搭建跨客户端和服务端的应用,结合了客户端应用丰富的互动和服务端渲染的改进性能。Server Components 和 Concurrent React 没有内在关系,但是被设计成能够最好地工作于并发特性,比如 Suspense 和流服务渲染。

Server Components is still experimental, but we expect to release an initial version in a minor 18.x release. In the meantime, we’re working with frameworks like Next.js, Hydrogen, and Remix to advance the proposal and get it ready for broad adoption.

Server Components 仍然处于试验阶段,但是我们期望在 18.x 的次要版本中发布一个初始版本。同时,我们正在与 Next.js, Hydrogen, and Remix 等框架合作,来推进这一提议,并为其广泛应用做好准备。


What’s New in React 18

New Feature: Automatic Batching

Batching is when React groups multiple state updates into a single re-render for better performance. Without automatic batching, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default. With automatic batching, these updates will be batched automatically:

批处理是 React 将多个状态更新放在一次重新渲染中,以获得更好的性能。没有自动批处理,我们只能在 React 事件处理中做批量更新。在 React 默认情况下, promises, setTimeout, native 事件处理,或者的其他处理事件都不会做批处理。通过自动批处理,这些更新将自动批处理。

// 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);

New Feature: Transitions

A transition is a new concept in React to distinguish between urgent and non-urgent updates.

  • Urgent updates reflect direct interaction, like typing, clicking, pressing, and so on.
  • Transition updates transition the UI from one view to another.

过渡是 React 里的新概念,用来区分紧急和非紧急更新。

  • 紧急更新指直接交互,比如打字、点击、按压等等。
  • 过渡更新是从一个 UI 视图过渡到另一个。

Urgent updates like typing, clicking, or pressing, need immediate response to match our intuitions about how physical objects behave. Otherwise they feel “wrong”. However, transitions are different because the user doesn’t expect to see every intermediate value on screen.

比如打字、点击、按压这类的紧急更新需要立即响应,以匹配我们对物理对象行为的直觉。否则,他们会觉得“错了”。然而,过渡是不同的,因为用户不期望在屏幕上看到所有的中间值。

For example, when you select a filter in a dropdown, you expect the filter button itself to respond immediately when you click. However, the actual results may transition separately. A small delay would be imperceptible and often expected. And if you change the filter again before the results are done rendering, you only care to see the latest results.

例如,当你在下拉菜单中选择一个筛选项时,你期望点击筛选项按钮本身时可以立即响应。然而,真正的结果可能分开过渡。小的延迟是不易被察觉而且往往是可以预料到的。如果在结果渲染完成之前再次改变筛选项,你仅关心看到最新的结果。

Typically, for the best user experience, a single user input should result in both an urgent update and a non-urgent one. You can use startTransition API inside an input event to inform React which updates are urgent and which are “transitions”:

典型地,为了最好的用户体验,一次用户输入应该导致紧急更新和不紧急更新。你可以在输入事件中使用 startTransition API 通知 React 哪些更新是紧急的,哪些是“过渡”的。

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

Updates wrapped in startTransition are handled as non-urgent and will be interrupted if more urgent updates like clicks or key presses come in. If a transition gets interrupted by the user (for example, by typing multiple characters in a row), React will throw out the stale rendering work that wasn’t finished and render only the latest update.

用 startTransition 包裹的更新将作为非紧急更新处理,如果进入更多紧急更新,比如点击或者按键,更新会被中断。如果过渡被用户打断(例如,在一行输入多个字符),React 将丢弃旧的没有完成的渲染工作,仅渲染最新更新。

  • useTransition: a hook to start transitions, including a value to track the pending state.
  • startTransition: a method to start transitions when the hook cannot be used.
  • useTransition:启用过渡的 hook,包括跟踪挂起状态值。
  • startTransition:当 hook 不能用时,启用过渡的方法。
Transitions will opt in to concurrent rendering, which allows the update to be interrupted. If the content re-suspends, transitions also tell React to continue showing the current content while rendering the transition content in the background (see the Suspense RFC for more info).

过渡在并发渲染中是可选的,它允许更新被中断。如果内容再次挂起,过渡也会告诉 React 继续展示当前内容,并在后台渲染过渡内容。

New Suspense Features

Suspense lets you declaratively specify the loading state for a part of the component tree if it’s not yet ready to be displayed:

Suspense 让你声明性地指定加载状态,对于组件树中还没准好呈现的部分。

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

Suspense makes the “UI loading state” a first-class declarative concept in the React programming model. This lets us build higher-level features on top of it.

Suspense 使得 “UI 加载状态”成为 React 编程模型中的第一类声明性概念。这让我们可以在此之上构建更高层次的特性。

We introduced a limited version of Suspense several years ago. However, the only supported use case was code splitting with React.lazy, and it wasn’t supported at all when rendering on the server.

几年前我们介绍过 Suspense 的有限版本。然而,唯一支持的使用场景是用 React.lazy 进行代码分割,并且在服务端渲染时完全不支持。

In React 18, we’ve added support for Suspense on the server and expanded its capabilities using concurrent rendering features.

在 React 18 中, 我们在服务端增加了对 Suspense 的支持,并且扩展了它使用并发渲染特性的能力。

Suspense in React 18 works best when combined with the transition API. If you suspend during a transition, React will prevent already-visible content from being replaced by a fallback. Instead, React will delay the render until enough data has loaded to prevent a bad loading state.

在 React 18 中 Suspense 结合 过渡 API 效果最好。如果在过渡过程中挂起,React 将阻止已经可见的内容被回退版本替代。相反,React 会延迟渲染,直到加载了足够的数据,以防止出现错误的加载状态。

New Client and Server Rendering APIs

In this release we took the opportunity to redesign the APIs we expose for rendering on the client and server. These changes allow users to continue using the old APIs in React 17 mode while they upgrade to the new APIs in React 18.

在这个版本中,我们有机会重新设计在客户端和服务端渲染公开的API。这些变化允许用户在 React 17 模式下继续使用旧的 API,同时在 React 18 中升级新的API。

React DOM Client

These new APIs are now exported from react-dom/client:

  • createRoot: New method to create a root to render or unmount. Use it instead of ReactDOM.render. New features in React 18 don’t work without it.
  • hydrateRoot: New method to hydrate a server rendered application. Use it instead of ReactDOM.hydrate in conjunction with the new React DOM Server APIs. New features in React 18 don’t work without it.

 这些新的 API 现在已经从 react-dom/client导出:

  • createRoot:创建根结点的新方法,用来渲染或者卸载。用它来代替 ReactDOM.render。React 18 中的新特性没有它将无法工作。
  • hydrateRoot:hydrate 服务端渲染应用的新方法。用它来代替ReactDOM.hydrate结合新 React Dom Server API 使用。React 18 中的新特性没有它将无法工作。

React DOM Server

 These new APIs are now exported from react-dom/server and have full support for streaming Suspense on the server:

  • renderToPipeableStream: for streaming in Node environments.
  • renderToReadableStream: for modern edge runtime environments, such as Deno and Cloudflare workers.

 这些新的 API 现在已经从react-dom/server导出,并且完全支持服务端流 Suspense。

  • renderToPipeableStream:用于Node 环境的流。
  • renderToReadableStream:用于当前运行环境,比如 Deno 和 Cloudflare workers。

The existing renderToString method keeps working but is discouraged.

现有的 renderToString 方法还可以用但不建议使用。

New Strict Mode Behaviors

In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React would unmount and remount trees using the same component state as before.

未来,我们将增加一个特性,允许 React 添加和删除 UI 的部分,同时保留状态。例如,当用户 tab 切换离开屏幕并返回时,React 应该能够立即显示前一个屏幕。为了实现这个,React 将使用和之前一样的组件状态卸载并重载树。

This feature will give React apps better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects assume they are only mounted or destroyed once.

这个特性将给 React 应用更好的开箱即用的性能,但是需要组件适应 effects 被多次的加载和销毁。大部分 effects 工作没有任何变化,但是有一些 effects 被设定为仅加载或者销毁一次。

To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

为了有助于呈现这些问题,React 18 介绍了 Strict Mode 新的仅开发检测。这个新的检测将自动卸载和重载每个组件,无论这个组件是第一次加载,还是在第二次加载时恢复前一个状态。

Before this change, React would mount the component and create the effects:

在这个变化之前,React 将挂载组件并创建 effects:

* React mounts the component.
  * Layout effects are created.
  * Effects are created.

With Strict Mode in React 18, React will simulate unmounting and remounting the component in development mode:

使用 React 18 的 Strict Mode,React 将在开发模式下模拟卸载和重载组件:

* 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.

New Hooks

useId

useId is a new hook for generating unique IDs on both the client and server, while avoiding hydration mismatches. It is primarily useful for component libraries integrating with accessibility APIs that require unique IDs. This solves an issue that already exists in React 17 and below, but it’s even more important in React 18 because of how the new streaming server renderer delivers HTML out-of-order. See docs here.

Note

useId is not for generating keys in a list. Keys should be generated from your data.

useId是在客户端和服务端生成唯一 ID 的新 hook,同时避免 hydration 不匹配。它主要用于组件库与需要唯一 ID 的可访问的 API 进行集成。这也解决了 React 17 及之前版本存在的问题,但是 useID 在 React 18 更加重要,因为新的流服务端渲染是如何无序的传递给HTML。

注意

useId不是用来生成列表的 key。列表 Key 应该从你的数据里生成。

useTransition

useTransition and startTransition let you mark some state updates as not urgent. Other state updates are considered urgent by default. React will allow urgent state updates (for example, updating a text input) to interrupt non-urgent state updates (for example, rendering a list of search results).

useTransitionstartTransition允许你将某些状态更新标记为不紧急。其他的状态更新默认为紧急的。React 将允许紧急更新(比如,更新文本输入)打断非紧急状态更新(比如:渲染搜索结果列表)。

useDeferredValue

useDeferredValue lets you defer re-rendering a non-urgent part of the tree. It is similar to debouncing, but has a few advantages compared to it. There is no fixed time delay, so React will attempt the deferred render right after the first render is reflected on the screen. The deferred render is interruptible and doesn’t block user input.

useDeferredValue允许你延迟重渲染树的非紧急部分。与防抖有点类似,但是相比较有一些优势。这里没有固定的时间延迟,所以 在第一次渲染呈现在屏幕之后,React 将试图延迟渲染。延迟渲染是可中断的,并且不会阻塞用户输入。

useSyncExternalStore

useSyncExternalStore is a new hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. It removes the need for useEffect when implementing subscriptions to external data sources, and is recommended for any library that integrates with state external to React. 

Note

useSyncExternalStore is intended to be used by libraries, not application code.

useSyncExternalStore是新的 hook,通过强制存储更新为同步,允许外部的存储支持并发读取。它移除了 useEffect 的必要性,并且推荐任何结合 React 外部状态的库去使用它。

注意

useSyncExternalStore用于库,而不是应用程序代码。

useInsertionEffect

useInsertionEffect is a new hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you’ve already built a CSS-in-JS library we don’t expect you to ever use this. This hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout. See docs here.

Note

useInsertionEffect is intended to be used by libraries, not application code.

useInsertionEffect是新的 hook,允许 CSS-in-JS 库解决渲染中插入样式的性能问题。除非你已经构建了 CSS-in-JS 库,否则我们不希望你使用它。这个 hook 将在 DOM 变化后运行,但是在布局 effects 拿到新的布局之前。这个 hook 解决了 React 17 及以前版本存在的问题,但是在 React 18 更加重要,因为 React 在并发渲染中向浏览器妥协,使其有机会重新计算布局。

注意

useInsertionEffect用于库,而不是应用程序代码。

 

终于完成这篇大作,所有翻译都是基本个人的理解,不一定准确,欢迎评论留言讨论。

posted @ 2022-05-30 18:08  shellon  阅读(334)  评论(0)    收藏  举报