Categories
React

How to Call a Function with React useEffect Only Once When the Component Mounts?

Spread the love

In many situations, we want to run the useEffect callback only when the component mounts.

In this article, we’ll look at how to call the useEffect callback only when the component mounts.

Pass in an Empty Array into the useEffect Hook

To run the useEffect hook callback only once when the component mounts, we just have to pass in an empty array into the 2nd argument of useEffect hook.

For instance, we can write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    console.log("mounted");
  }, []);

  return <div className="App"></div>;
}

We just pass in an empty array into useEffect and the callback would only run once.

So we only see 'mounted' logged when the component is mounted.

We can also move the useEffect hook call into its own function if we use it in multiple places:

import React, { useEffect } from "react";

const useMountEffect = (fun) => useEffect(fun, []);

export default function App() {
  useMountEffect(() => {
    console.log("mounted");
  });

  return <div className="App"></div>;
}

We create the useMountEffect hook that takes the fun function and call useEffect in the function the same way we did before.

Run Code When a Component Unmounts

To run code when a component unmounts, all we have to do is to return a function in the useEffect hook.

For instance, we can write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    console.log("mounted");

    return () => {
      console.log("unmounted");
    };
  }, []);

  return <div className="App"></div>;
}

We return a function that logs 'unmounted' .

We’ll see it run when we unmount the component.

Conclusion

To run a function only once when a React component mounts, we just have to pass in an empty array as the 2nd argument of the useEffect hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *