Skip to content
the poor coder

React useEffect Hook

Poor Man
Published
Reading time
1 min read

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:

JavaScript

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:

JavaScript

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC