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)