Back to results for “useRef & forwardRef”
React › Concurrent Hooks (useTransition, useDeferredValue & useLayoutEffect)

What is useLayoutEffect and how is it different from the regular useEffect hook?

Intermediate

Answer

useLayoutEffect runs right after React updates the screen but before the browser actually paints anything visible to the user. This is useful when you need to measure something on the screen, like an element's size, and make an adjustment before the user ever sees a flicker. Regular useEffect runs a little later, after the browser has already painted.
function Tooltip() {
  const ref = useRef(null);
  const [height, setHeight] = useState(0);

  useLayoutEffect(() => {
    setHeight(ref.current.getBoundingClientRect().height);
  }, []);

  return <div ref={ref}>Tooltip content, height is {height}</div>;
}
Real-world example A tooltip component measures its own height using useLayoutEffect so it can correctly position itself above a button before the user ever sees it flicker or jump into place.

Common follow-ups: Why can using useLayoutEffect too often make an app feel slower than using useEffect?;In what situation would using regular useEffect actually cause a visible flicker?