问题
What is the difference between useMutationEffect
and useLayoutEffect
in term of usage?
I have read all available material online including (but not limited to)
- Hooks Reference
- 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:
- useMutationEffect
- useLayoutEffect
- 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
.
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.
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.
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