TLDR: useLayoutEffect runs before DOM mutations are painted. useEffect runs after DOM mutations are painted.
In a nutshell
useLayoutEffect hook lets you run code after React has performed all its DOM mutations, but before the browser has had a chance to paint those changes. Updates scheduled inside
useLayoutEffect will be flushed synchronously which means it’ll block the browser paint until finished.
useLayoutEffect blocks the browser from painting, it’s preferable to use
useEffect in most cases. But if you must run some code before the next paint,
useLayoutEffect can be preferable.
- useLayoutEffect – React docs
- useEffect vs useLayoutEffect – Kent C. Dodds
- React useLayoutEffect vs. useEffect with examples – Ohans Emmanuel
- List some concrete examples of when
useLayoutEffectmight be preferable.