React Hooks:“useMutationEffect"和“useLayoutEffect"有什么区别? [英] React Hooks: What is the difference between 'useMutationEffect' and 'useLayoutEffect'?

查看:65
本文介绍了React Hooks:“useMutationEffect"和“useLayoutEffect"有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

useMutationEffectuseLayoutEffect 在用法上有什么区别?

What is the difference between useMutationEffect and useLayoutEffect in term of usage?

我已在线阅读所有可用材料,包括(但不限于)

I have read all available material online including (but not limited to)

  1. 钩子参考
  2. 肯特的博文

useEffect 和其他两个钩子的区别很明显.但是 useMutationEffectuseLayoutEffect 的区别还不清楚.

Difference between useEffect and other two hooks is clear. but difference between useMutationEffect and useLayoutEffect is still not clear.

我知道执行顺序是:

  1. useMutationEffect
  2. useLayoutEffect
  3. useEffect

推荐答案

首先,你要了解渲染的不同阶段.

用户可见的 DOM 突变必须在下一次绘制之前同步触发,以便用户不会察觉到视觉上的不一致.对于这种特定情况,我们应该使用 useMutationEffectuseLayoutEffect 来执行阻塞视觉更新.这两者之间唯一的区别是,如果我们想从 DOM 中读取 Layout,我们应该使用 useLayoutEffect.否则,我们应该使用useMutationEffect.

A DOM mutation that is visible to the user must fire synchronously before the next paint so that the user does not perceive a visual inconsistency. We should use either useMutationEffect or useLayoutEffect for this specific case to perform blocking visual updates. The only difference between these two is we should use useLayoutEffect if we want to read Layout from the DOM. Otherwise, we should use useMutationEffect.

  1. useMutationEffect

它在布局阶段之前同步触发,即在 React 执行其 DOM 更改的同一阶段.使用它来阻止自定义 DOM 突变,而无需进行任何 DOM 测量/读取布局.

It fires synchronously before Layout phase i.e. during the same phase that React performs its DOM mutations. Use it to perform blocking custom DOM mutations without taking any DOM measurement/reading layout.

  1. useLayoutEffect

它在所有 DOM 突变之后但在 Paint 阶段之前同步触发.使用它从 DOM 中读取布局(样式或布局信息),然后根据布局执行阻止自定义 DOM 突变.

It fires synchronously after all DOM mutations but before Paint phase. Use this to read layout(styles or layout information) from the DOM and then perform blocking custom DOM mutations based on layout.

  1. useEffect

它在渲染提交到屏幕后运行,即在布局和绘制阶段之后.尽可能使用它以避免阻止视觉更新.

It runs after the render is committed to the screen i.e. after Layout and Paint phase. Use this whenever possible to avoid blocking visual updates.

更新:useMutationEffect 钩子已从 钩子 API 在这个 PR 中.(来源:Dhaval Patel)

Update: useMutationEffect hook has been removed from Hooks API in this PR. (Credits: Dhaval Patel)

这篇关于React Hooks:“useMutationEffect"和“useLayoutEffect"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆