React useEffect Hooks

 useEffect hook is a built-in function that allows you to perform side effects in functional components. Side effects are anything that happens outside of the component, such as fetching data, updating the document title, or setting up event listeners.

The useEffect hook takes a callback function as its first argument, and an array of dependencies as its second argument. The callback function is where you perform your side effects, and the dependencies determine when the callback function should be called.

Here’s an example of how you might use useEffect to fetch data from an API and update the component state:

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

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))
  }, []);

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

				
			

In this example, we first import useState and useEffect from the React library. We then declare a new state variable called users and a function called setUsers to update the state. The initial value of users is an empty array.

We then declare an useEffect function that fetches data from an API using the fetch function. Once the data is retrieved, we update the users state using setUsers. We also pass an empty array as the second argument to useEffect, which tells React to only run the effect once, when the component mounts.

Finally, we render the list of users using the map function and the users state.

When the component mounts, the useEffect function is called, which fetches data from the API and updates the users state. The component then re-renders with the updated state value.

useEffect is a powerful hook that allows you to perform side effects in functional components. By using it, you can write cleaner and more concise code that is easier to understand and maintain.

Join To Get Our Newsletter
Spread the love