React useEffect Hook

React useEffect Hook

The useEffect hook in React is used to manage side effects in functional components. Side effects are anything that affects the state of your application outside of the current scope. This could include things like updating the DOM, making API calls, or setting up event listeners.

The useEffect hook allows you to run side effects after every re-render of your component. It takes two arguments:

  • The first argument is a function that will be run after every re-render of your component.
  • The second argument is an array of dependencies. This array specifies which variables the effect depends on, and the effect will only be run if one of these variables changes.

Here's an example of using the useEffect hook to fetch data from an API:


import { useState, useEffect } from 'react';

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

    useEffect(() => {
        fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => setData(data));
    }, []);

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

In this example, we define a state variable data and initialize it to an empty array. We then use the useEffect hook to fetch data from an API and update the data state when the component mounts. The empty array as the second argument to useEffect means that the effect will only run once, when the component mounts.

The useEffect hook can also be used to clean up side effects when your component unmounts. To do this, simply return a function from the effect:


useEffect(() => {
    // run side effect
    return () => {
        // clean up side effect
    };
}, []);

In this example, the function returned from the effect will be run when the component unmounts. This is useful for things like removing event listeners or clearing intervals that were set up in the effect.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe