简体   繁体   English

React 18 中 hooks 的顺序是什么?

[英]What is the order of hooks in React 18?

React 18 implements a new hook: useInsertionEffect . React 18实现了一个新的钩子: useInsertionEffect

So with useEffect and useLayoutEffect , what is the order of these 3 hooks at component generation?那么对于useEffectuseLayoutEffect ,这 3 个钩子在组件生成时的顺序是什么?

According to the React Docs :根据React 文档

useInsertionEffect使用插入效果

It fires synchronously before all DOM mutations.它在所有 DOM 突变之前同步触发。 Use this to inject styles into the DOM before reading layout in useLayoutEffect .useLayoutEffect中读取布局之前,使用它来将 styles 注入 DOM。 So it runs before useLayoutEffect .所以它在useLayoutEffect之前运行。

useLayoutEffect使用布局效果

It fires synchronously after all DOM mutations.它在所有 DOM 变更同步触发。 Use this to read layout from the DOM and synchronously re-render.使用它从 DOM 读取布局并同步重新渲染。

useEffect使用效果

It will run after the render is committed to the screen.它将在渲染提交到屏幕后运行。 So it runs after useLayoutEffect .所以它在useLayoutEffect之后运行。

Therefore the order of running is:因此运行顺序为:

  1. useInsertionEffect使用插入效果
  2. useLayoutEffect使用布局效果
  3. useEffect使用效果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM