Search

React useEffect Hooks

  • Share this:

The `useEffect` hook allows you to specify a function that will be run after the component has been rendered. This function is known as an effect. Effects can be used to perform a variety of tasks, such as fetching data, setting up subscriptions, or changing the DOM.

Here is an example of how you might use the `useEffect` hook to fetch data in a React functional component:

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    fetch('https://my-api.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // The empty array means this effect will only run once when the component mounts

  return data ? <div>{data}</div> : <div>Loading...</div>;
}

The `useEffect` hook takes a function as an argument and an optional array of dependencies. The function will be run after the component has rendered, and the effect will be "clean up" when the component unmounts or the dependencies change.

You can also use the `useEffect` hook to perform cleanup tasks, by returning a function from the effect. For example:

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    const subscription = data.subscribe(setData);
    return () => {
      // This function will be run when the component unmounts or the dependencies change
      subscription.unsubscribe();
    };
  }, [data]); // This effect will run whenever data changes

  return data ? <div>{data}</div> : <div>Loading...</div>;
}

I hope this helps! Let me know if you have any more questions.

 

Tags:

About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.