Categories
JavaScript React

React Hooks Equivalent of componentDidMount

Spread the love

When we transition from creating class component to function component, one of things we have to do is find the hook equivalents of the life cycle hooks in class components.

One of the life cycle methods that are used a lot is the componentDidMount method.

It loads when the component is first mounted.

To do the same thing in function components, we use the useEffect hook with an empty array in the 2nd argument.

This lets us commit side effects once when the component first loads.

To use it, we write:

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

export default function App() {
  const [data, setData] = useState({});

  const getData = async () => {
    const res = await fetch("https://api.agify.io/?name=michael");
    const data = await res.json();
    setData(data);
  };

  useEffect(() => {
    getData();
  }, []);

  return <div>{data.name}</div>;
}

We reference the useEffect hook with a callback that calls the getData function.

getData just makes a GET request to an API and get some data. Then it set it as the value of the data state.

The empty array indicates that the callback only loads once when the component first loads.

This is because the array has the values to watch for, and we watch nothing, so it only loads once.

Then we return the data we want to display.

We can have more than one reference to useEffect unlike componentDidMount, so we don’t have to put everything in one callback.

Instead, we can have multiple instances of useEffect with empty arrays as the 2nd argument.

App just loads the data on first load and displays it.

Leave a Reply

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