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.
| Concern | useEffect | useLayoutEffect |
|---|---|---|
| Primary use | External synchronization | Layout measurement or visual adjustment |
| Painting | Usually lets the browser paint first | Runs before the browser repaints |
| Cost | Does not normally block paint | Can block paint and hurt performance |
| Default choice | Yes | Only 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>;
}