What are differences between useEffect and useLayoutEffect?
When it runs:
useEffect
: After the browser has painted the updated DOM.useLayoutEffect
: After the DOM mutations but before the browser paints.
Blocking behavior:
useEffect
: Non-blocking; the browser can paint before it runs.useLayoutEffect
: Blocking; delays browser painting until it completes.
When we should use useLayoutEffect
instead of useEffect
?
You should use useLayoutEffect
instead of useEffect
when you need to perform DOM-related operations that must happen before the browser paints to ensure a consistent user experience.
import React, { useLayoutEffect, useRef } from "react";
function PreventFlicker() {
const divRef = useRef();
useLayoutEffect(() => {
// Apply style immediately after DOM mutation
divRef.current.style.backgroundColor = "red";
}, []);
return <div ref={divRef}>Styled Immediately</div>;
}
If useEffect
were used, the browser would paint the unstyled component first and then after a short time, apply new style => causing a visible flicker.