Delving Developer

useLayoutEffect vs useEffect: Differences, Examples and When to Use Them in React

Eddie Cunningham
Eddie Cunningham
3 min readReact.js
Cover Image for useLayoutEffect vs useEffect: Differences, Examples and When to Use Them in React

If you're building a SPA (single page app) using React, you probably know all about hooks like useEffect and useLayoutEffect. These powerful tools let you perform tasks like data fetching, updating the DOM, and more. In this article, we'll compare and contrast useLayoutEffect and useEffect, and see how each of these hooks operates in the exciting world of React.

What is useEffect in React?link

At its essence, useEffect is a hook that lets you add side effects to your React components. Side effects are any activities that aren't related to rendering or updating the UI. You can use useEffect to handle anything from fetching data from a server to subscribing to updates from a WebSocket, and updating the title of the document.

In this example, useEffect gets used to fetch data from an API.

import { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://example.com/data')
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  return <>{data ? <div>{JSON.stringify(data)}</div> : <p>Loading...</p>}</>;
}

As you can see, this useEffect gets triggered when the component mounts. The empty dependency array [] indicates that this effect should only run once, when the component first renders.

What is useLayoutEffect in React?link

In React, useLayoutEffect is a hook that lets you operate on the DOM as soon as it is ready to be modified. This is great when you want to take care of any UI changes that you need to do, quickly.

Here's an example where useLayoutEffect gets used to change the background color of a div element:

import { useState, useLayoutEffect } from 'react';

function MyComponent() {
  const [color, setColor] = useState('blue');

  useLayoutEffect(() => {
    document.querySelector('#my-div').style.backgroundColor = color;
  }, [color]);

  return (
    <div>
      <button onClick={() => setColor('red')}>Red</button>
      <button onClick={() => setColor('green')}>Green</button>
      <button onClick={() => setColor('blue')}>Blue</button>
      <div id="my-div">This is my div</div>
    </div>
  );
}

This useLayoutEffect gets triggered every time color changes. It instantly updates the background color of the div element instead of waiting for the next render.

Differences Between useEffect and useLayoutEffect in Reactlink

While both useLayoutEffect and useEffect seem similar, there are differences that set them apart.

  • Timing: useEffect works just after the rendering, while useLayoutEffect starts before the repaint of the screen.

  • Blocking: When a developer uses useLayoutEffect with a long-running sync task, it can stop the browser from showing the webpage. In contrast, useEffect will not block the browser in this way.

  • SSR: The useEffect is safe to use while Server Side Rendering (SSR), but useLayoutEffect can cause some issues with layout mismatches.

Considering these differences, If you want to update the DOM quickly, use useLayoutEffect. If you expect the effect to be time-consuming or if it doesn’t need immediate updates, use useEffect

Conclusionlink

The difference between useLayoutEffect and useEffect in React is one of the more critical distinctions you need to know when building high-quality React web apps. By studying each hook and exploring different examples in this article, you can gain deeper insight into the capabilities of this great toolset. Understanding their features and benefits, where to use each one, we hope you are now in a better position to use useLayoutEffect and useEffect to create powerful React applications that solve the most pressing problems for you and your clients.