AceDevHub
Intermediate React Interview QuestionsIntermediateComparison

React · Question 48

What is the difference between useEffect and useLayoutEffect?

Direct answer

useEffect is the default choice for synchronizing with external systems, while useLayoutEffect runs earlier around layout and can block painting, so it is reserved for work that must measure or adjust layout before the user sees it.

ConcernuseEffectuseLayoutEffect
Primary useExternal synchronizationLayout measurement or visual adjustment
PaintingUsually lets the browser paint firstRuns before the browser repaints
CostDoes not normally block paintCan block paint and hurt performance
Default choiceYesOnly when visual timing requires it
Tooltip.jsx
function Tooltip() {
  const ref = useRef(null);

  useLayoutEffect(() => {
    const rect = ref.current.getBoundingClientRect();
    // Measure before the browser paints the final position.
    positionTooltip(rect);
  }, []);

  return <div ref={ref}>Tooltip</div>;
}