How to use useEffect in React.js

Posted by

In React.js, the useEffect hook is used to perform side effects in functional components. Side effects include things like data fetching, subscriptions, or manually changing the DOM.

To use the useEffect hook in your React functional component, you’ll first need to import it from the react library:

import React, { useEffect } from 'react';

Next, you can use the useEffect hook inside your functional component. The basic syntax for the useEffect hook is as follows:

useEffect(() => {
  // code to run on component mount
  // optional code to run on component unmount
}, [dependencies]);

The first argument to the useEffect hook is a callback function that contains the code you want to run as a side effect. This code will run after the component has rendered. The second argument is an optional array of dependencies. If any of the dependencies change, the useEffect hook will rerun.

Here’s an example of how you might use the useEffect hook to fetch data from an API:

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

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

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const result = await response.json();
      setData(result);
    };

    fetchData();
  }, []);

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

In this example, we use the useState hook to create a state variable data that will hold the fetched data. We then use the useEffect hook to fetch the data from the API when the component mounts. Since we pass an empty array as the second argument, the effect runs only once, on component mount.

Remember that the useEffect hook can also be used for cleanup. If the effect returns a function, React will call this cleanup function when the component unmounts. Here’s an example:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // code to run on component mount
    return () => {
      // code to run on component unmount
    };
  }, []);

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

In this example, the cleanup function runs when the component unmounts. This can be useful for tasks like unsubscribing from a subscription or canceling a network request.

Overall, the useEffect hook is a powerful tool for managing side effects in React functional components. By using this hook, you can perform tasks like data fetching, DOM manipulation, and cleanup in a clean and concise way.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@nickolayarbuzov6149
3 months ago

Exellent ! Please, continue