DEV Community

Esther Itolima
Esther Itolima

Posted on

useEffect vs useEffectOnce

As a developer, you've probably encountered React's useEffect hook, which is used for handling side effects in functional components. While useEffect is a powerful tool, you may not be aware of its more specialized variant, useEffectOnce. In this post, we'll explore the differences between these two hooks and when to use each one.

useEffect()

The useEffect hook is a tool that allows you to execute side effects in functional components. Side effects are actions that occur outside of a component's state updates, such as fetching data, setting timers, or updating the DOM.

When you use useEffect, you provide a callback function that will be executed after each render cycle. This function may have side effects that need to be cleaned up when the component is unmounted or re-rendered. To do this, you can return a cleanup function from the useEffect callback

Here's an example of how to use useEffect to fetch data from an API:

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://my-api.com/data');
      const jsonData = response.data;
      setData(jsonData);
    }

    fetchData();
  }, []);

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}


export default MyComponent
Enter fullscreen mode Exit fullscreen mode

In this example, we define a state variable called data and initialize it to null. We then use useEffect to fetch data from an API and update the data state variable with the response. The [] empty array as second argument tells React to only execute the callback once, after the initial render.

useEffectOnce

While useEffect is a great general-purpose tool, there are cases where you only need to execute a side effect once, when the component is mounted. This is where useEffectOnce comes in.

useEffectOnce is a custom hook that wraps useEffect and provides a more concise way to execute a side effect only once.

_A custom hook is simply a JavaScript function that starts with the prefix "use". This prefix is important, as it tells React that this function is a hook and can be used with the use keyword within a functional component. Custom hooks can use other built-in hooks such as useState, useEffect, useCallback, etc., to build the desired functionality.
_

Here's what the implementation looks like:

import { EffectCallback, useEffect } from 'react'

export function useEffectOnce(effect: EffectCallback) {
  useEffect(effect, []);
}

Enter fullscreen mode Exit fullscreen mode

As you can see, useEffectOnce accepts a single argument, which is the callback function that will be executed once. It then calls useEffect with the same callback and an empty array as the second argument, which tells React to only execute the callback once, after the initial render.

Here's an example of how to use useEffectOnce to initialize a third-party library:

import { useEffectOnce } from './useEffectOnce';



function MyComponent() {
const [data, setData] = useState({
name: 'John Doe'
});

  useEffectOnce(() => {
    console.log('Triggered only once, on mount', { data })
  });

  return <div>My Component</div>;
}

Enter fullscreen mode Exit fullscreen mode

In this example, we import the useEffectOnce hook from a separate file and use it to display the data. The callback function is executed only once, after the initial render.

When to use useEffect or useEffectOnce?

So, when should you use useEffect and when should you use useEffectOnce?

As a general rule, you should use useEffect for side effects that need to be executed on every render, such as updating the DOM based on state changes or fetching data from an API based on props. Use useEffectOnce for side effects that need to be executed only once, such as initializing a third-party library or registering event listeners.

If you're unsure which hook to use, you can always start with useEffect and refactor to useEffectOnce if you find it necessary to use.

In conclusion, both useEffect and useEffectOnce are powerful tools for handling side effects in React functional components. Knowing when to use each hook is important for writing efficient and maintainable code. As a general rule, use useEffect for side effects that need to be executed on every render, and useEffectOnce for side effects that need to be executed only once.

By understanding the differences between these two hooks and using them appropriately, you can write cleaner and more effective code in your React projects.

Do well to comment which one you have used.

Reference
https://reactjs.org/docs/hooks-effect.html
https://www.freecodecamp.org/news/react-useeffect-absolute-beginners/
https://blog.logrocket.com/useeffect-hook-complete-guide/
https://www.turing.com/blog/custom-react-js-hooks-how-to-use/
https://www.freecodecamp.org/news/how-to-create-react-hooks/
https://blog.logrocket.com/create-your-own-custom-react-hooks/
https://betterprogramming.pub/react-custom-hooks-with-real-life-examples-c259139c3d71
https://morioh.com/p/2784310361ef

Top comments (0)