The Bloggo

Understanding useEffect(), useLayoutEffect(), and useInsertionEffect() in React

React’s hooks API has revolutionized the way we write components and manage their lifecycle. Among these hooks, useEffect, useLayoutEffect, and the relatively newer useInsertionEffect play crucial roles in side effect management. In this post, we’ll delve into each of these hooks, their uses, and some practical examples.

useEffect

useEffect is perhaps the most commonly used hook for handling side effects in functional components. It replaces several lifecycle methods from class components, such as componentDidMount, componentDidUpdate, and componentWillUnmount.

When to Use useEffect

Use useEffect for:

  • Data fetching
  • Subscriptions
  • Manually changing the DOM

Example

Let’s fetch user data from an API:

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

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`https://api.example.com/users/${userId}`);
      const userData = await response.json();
      setUser(userData);
    };

    fetchData();
  }, [userId]);

  return (
    <div>
      {user ? <p>{user.name}</p> : <p>Loading...</p>}
    </div>
  );
}

useLayoutEffect

useLayoutEffect is similar to useEffect, but it fires synchronously after all DOM mutations. This makes it ideal for reading layout from the DOM and re-rendering, ensuring minimal flicker.

When to Use useLayoutEffect

Use useLayoutEffect for:

  • Measuring DOM elements
  • Animations

Example

Measuring a DOM element’s height:

import React, { useState, useLayoutEffect, useRef } from 'react';

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

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

  return (
    <>
      <div ref={ref}>Measure me</div>
      <p>The above div is {height}px tall</p>
    </>
  );
}

useInsertionEffect (New in React 18)

useInsertionEffect is a new addition in React 18. It’s used for CSS-in-JS libraries to inject styles into the DOM before browser paint, avoiding flickering or layout shift.

When to Use useInsertionEffect

Use useInsertionEffect for:

  • Injecting styles with CSS-in-JS libraries

Example

Using useInsertionEffect with a hypothetical CSS-in-JS library:

import React, { useInsertionEffect } from 'react';
import { createStyle } from 'my-css-in-js-library';

function StyledComponent() {
  useInsertionEffect(() => {
    createStyle('.my-style { color: blue; }');
  }, []);

  return <div className="my-style">I'm blue!</div>;
}

Conclusion

Understanding when and how to use useEffect, useLayoutEffect, and useInsertionEffect is key to mastering React’s hooks API. While useEffect is a versatile tool for various side effects, useLayoutEffect offers a solution for cases where layout measurements and synchronous re-renders are necessary. The new useInsertionEffect further expands React’s capabilities, particularly in conjunction with CSS-in-JS libraries.

Remember, the best hook to use depends on the specific scenario. Experiment and refer to the official React documentation for deeper insights.

Subscribe to Porto newsletter and stay updated.

Don’t miss anything. Get all the latest posts delivered straight to your inbox. It’s free!

Subscription Form
Scroll to Top