Hackforge Academy

Category: react

useEffect vs useLayoutEffect

Published on 27 Oct 2026

Explanation

useEffect is the default for synchronizing with external systems. useLayoutEffect runs after DOM mutations but before the browser paints, making it suitable for layout measurements that must happen before the user sees the result.

Code:

useEffect(() => {
  document.title = title;
}, [title]);

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

Explanation

Use useLayoutEffect when you must measure layout and synchronously apply a correction before the browser paints, such as positioning a tooltip. It can block painting, so keep the work small.

Code:

const ref = useRef(null);
const [height, setHeight] = useState(0);

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

Explanation

Most effects do not need to block the browser from painting. Prefer useEffect for subscriptions, data synchronization, and document updates unless visual flicker shows that a pre-paint layout effect is necessary.

Code:

useEffect(() => {
  const connection = connectToRoom(roomId);
  return () => connection.disconnect();
}, [roomId]);

Explanation

Fetching data does not generally require a pre-paint effect. Use useEffect or a framework/data-fetching library so the browser can paint without being blocked by layout work.

Code:

useEffect(() => {
  const controller = new AbortController();
  fetch('/api/products', { signal: controller.signal })
    .then((res) => res.json())
    .then(setProducts);
  return () => controller.abort();
}, []);

Explanation

useLayoutEffect needs a browser layout and does not run during server rendering. If a component relies on layout measurement, consider rendering it only on the client or using a layout that does not require pre-paint measurement.

Code:

function Tooltip() {
  const ref = useRef(null);
  const [position, setPosition] = useState({ top: 0, left: 0 });

  useLayoutEffect(() => {
    const rect = ref.current.getBoundingClientRect();
    setPosition({ top: rect.bottom, left: rect.left });
  }, []);

  return <div ref={ref} style={{ position: 'absolute', ...position }}>Tip</div>;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community