DEV Community

Kumar Nitesh
Kumar Nitesh

Posted on

Handling Side Effects with useEffect: A Comprehensive Guide

Introduction:
In the previous articles, we explored the useReducer and useState hooks and learned how they can be used to manage state in React applications. In this article, we will cover another important hook - the useEffect hook - and see how it can be used to handle side effects in our components.

What is useEffect:
The useEffect hook allows you to perform side effects in your functional components. It runs after the component has rendered, and can be used to fetch data, update the DOM, or perform any other operations that have an effect on the component or outside of it.

Example:
Let's look at a simple example to see how useEffect works. We'll create a component that fetches data from an API and displays it on the screen.

Code:

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

const DataFetcher = () => {
  const [data, setData] = useState(null);

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

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.title}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Explanation:
In this example, we use the useEffect hook to fetch data from an API and update the state when the data is received. The hook takes a function as its first argument, which is the effect function. The effect function contains the code to perform the side effect.

The second argument to the useEffect hook is an array of dependencies, which tells React when to re-run the effect. In this example, we passed an empty array, which means that the effect will only run once, when the component is first mounted.

In the effect function, we use the fetch API to fetch data from the API and then update the state with the received data using the setData function. When the state is updated, the component is re-rendered with the new data.

Conclusion:
The useEffect hook is a powerful tool for handling side effects in your React components. In this article, we looked at a simple example of how to use the useEffect hook to fetch data from an API and display it on the screen. With the useEffect hook, you can handle any type of side effect in your components, from data fetching to updating the DOM.

In this series of articles, we've covered the useRef, useReducer, useState, and useEffect hooks, and learned how they can be used to manage state and side effects in React applications. I hope this has been a helpful guide for you. If you have any questions, feel free to ask in the comments below.

Top comments (0)