What is the difference between useLayoutEffect and useEffect?

What is the difference between useLayoutEffect and useEffect?
October 03, 2024

In React, useEffect and useLayoutEffect are two hooks used for side effects, but they work slightly differently.

useEffect runs the effect after the component renders and the paint has been done. This means it doesn't block the rendering process, allowing the browser to update the screen first.

It's useful for tasks like fetching data, subscription, or changing the DOM very late.

Here's a simple example of useEffect:

import { useEffect } from 'react';


function MyComponent() {
    useEffect(() => {
        document.title = 'Hello!';
    });


    return <div>Hello World</div>;
}

In this example, useEffect runs after the render, changing the document title to 'Hello!'.

This won't delay the painting of the page.

useLayoutEffect, on the other hand, runs after the DOM update but before the browser paints. It blocks the screen update until it completes.

It can be useful for measuring DOM elements and reading layout before another paint happens.

Here's how you could use useLayoutEffect:

import { useLayoutEffect, useRef } from 'react';


function Example() {
  const divRef = useRef(null);


  useLayoutEffect(() => {
    const { height } = divRef.current.getBoundingClientRect();
    console.log('Height:', height);
  }, []);


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

In this case, useLayoutEffect ensures we read the div's height before painting.

It is Used for:

  • Form Auto Resize: If you need to measure and adjust form sizes before they appear onscreen to prevent awkward jumps, use useLayoutEffect.
  • Synchronized Animations: When working on animations based on user actions that need synchronized reaction, useLayoutEffect helps calculate positions.
  • Dynamic Styling: Use it to read dimensions or styles from the DOM to apply new styles correctly before users see the page.
  • Canvas: If drawing on a canvas requires item positioning based on other elements, useLayoutEffect ensures element look before the canvas renders

Both hooks are handy depending on timing needs. Using them wisely helps manage component behavior and improve performance.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates