40. What is the difference between useEffect and useLayoutEffect in React?
medium

In React, useEffect and useLayoutEffect are two hooks used to handle side effects in functional components. While they share similarities, there are key differences in their timing, behavior, and use cases.


Explanation of Key Concepts

  • useEffect: A hook that runs asynchronously after the DOM has been updated and painted.
  • useLayoutEffect: A hook that runs synchronously after DOM mutations but before the browser paints the screen.

Key Differences

  • Timing:
    • useEffect: Executes after the browser has painted the UI (asynchronous).
    • useLayoutEffect: Executes before the browser paints, right after DOM changes (synchronous).
  • Blocking Behavior:
    • useEffect: Non-blocking, runs asynchronously.
    • useLayoutEffect: Blocking, runs synchronously.

Common Use Cases

  • useEffect:
    • Fetching data from an API
    • Setting up subscriptions (e.g., WebSocket connections)
    • Logging or analytics tracking
    • Adding and removing event listeners
  • useLayoutEffect:
    • Measuring DOM elements (e.g., for animations or layouts)
    • Adjusting DOM properties or styles based on calculations
    • Fixing UI synchronization issues

Example: useEffect vs useLayoutEffect

import React, { useEffect, useLayoutEffect } from 'react';

function Example() {
  const ref = React.createRef();

  useEffect(() => {
    console.log('useEffect: Runs after DOM paint');
  });

  useLayoutEffect(() => {
    console.log('useLayoutEffect: Runs before DOM paint');
    console.log('Element width:', ref.current.offsetWidth);
  }, []);

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

In this example, useLayoutEffect runs synchronously after the DOM mutation and before painting, allowing access to layout properties like offsetWidth before the screen is updated. On the other hand, useEffect runs asynchronously after the paint, making it suitable for non-blocking side effects.


Conclusion

useEffect is ideal for asynchronous tasks like data fetching or logging, while useLayoutEffect is suitable for synchronous operations that require immediate DOM access before painting. Understanding when to use each helps build more efficient and responsive React components.