React Hooks: What is the difference between 'useMutationEffect' and 'useLayoutEffect'?

一曲冷凌霜 提交于 2021-02-18 10:30:27

问题


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. Hooks Reference
  2. Blog post by Kent

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

I know the order of execution is:

  1. useMutationEffect
  2. useLayoutEffect
  3. useEffect

回答1:


First, you have to understand the different phases of Rendering.

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

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

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.

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



来源:https://stackoverflow.com/questions/53513872/react-hooks-what-is-the-difference-between-usemutationeffect-and-uselayoutef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!