React’s useEffect Hook: A Complete Guide for Better State Management

Ifeanyi Emmanuel
3 min readFeb 3, 2023
useEffect hook

React is an amazing JavaScript library for building user interfaces, and the useEffect hook is one of its most valuable tools. The useEffect hook enables you to handle side effects in a flexible, efficient, and reusable manner. In this comprehensive guide, we’ll delve into what side effects are, how the useEffect hook operates, and how to use it to its full potential.

What are Side Effects in React?

A side effect is any behavior that changes something outside of the component, such as making an API call, altering the DOM, or setting a timer. In traditional React, these side effects were managed using component lifecycle methods, such as componentDidMount and componentDidUpdate. However, the useEffect hook makes it easier to manage side effects in a more flexible and efficient way.

How Does the useEffect Hook Work?

The useEffect hook takes two arguments: a function that performs the side effect, and an array of dependencies. The dependencies are the values from your component’s state or props that you want to watch for changes. When any of these values change, the useEffect hook will rerun the function, allowing you to update your component accordingly.

Here’s a simple example of how to use the useEffect hook to make an API call and update your component’s state with the data:

import React, { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://my-api.com/statistics')
.then(response => response.json())
.then(data => setData(data));
}, []);
return data ? `${data.name}` : `Loading...`;
}

In this scenario, the useEffect hook is calling the fetch function when the component is first mounted, and setting the data in the component’s state when the API call is complete. The second argument, an empty array, means that the useEffect hook will only run once, when the component is first mounted.

The Cleanup Function

In addition to performing the side effect, the useEffect hook can also return a cleanup function that will be called when the component is unmounted, or when the useEffect hook is rerun with different dependencies. This cleanup function is useful for removing event listeners, clearing timers, or undoing other changes that were made in the side effect.

Here’s an example of how to use the useEffect hook to add a resize event listener, and returning a cleanup function to remove the listener when the component is unmounted:

import React, { useState, useEffect } from 'react';
function Example() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return `The window width is ${width}px`;
}

In this scenario, the useEffect hook is adding a resize event listener to the window object when the component is mounted, and returning a cleanup function to remove the listener when the component is unmounted. This ensures that the listener will no longer continue to run and cause memory leaks

Additionally, the useEffect hook allows for updating the state of the component in response to changes in the window size, by re-running the effect whenever the window is resized. This ensures that the component remains in sync with the current window size, and provides a dynamic, responsive experience for the user. By using useEffect, the component is able to effectively manage its own behavior and state, without relying on external components or libraries.

Furthermore, the useEffect hook provides a convenient and efficient way to handle window resize events and update the component’s state in real-time. This helps to enhance the user experience by dynamically adjusting the layout and content based on the current window size. The useEffect hook also helps to simplify the code by encapsulating the logic for handling window resize events within the component, reducing the need for complicated event handling code or additional libraries. Overall, the useEffect hook provides a powerful and flexible tool for managing the behavior of React components in response to changes in the environment.

--

--