score:23

Accepted answer

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)


Related Query

More Query from same tag