Exploring React Hooks: A Comprehensive Tutorial Series — Part 2: useEffect

Elevate Your React Development with Hooks — Simplifying State and Lifecycle Management

Vinojan Veerapathirathasan
4 min readJun 28, 2024
React Hooks: useEffect

Hi there 👋,

Welcome to the second part of the React Hooks series! In this part we will explore about useEffect hook with the practical explanation. Let’s deep dive into the topic 🎊

useEffect

The useEffect hook is a versatile part of React Hooks API that allows you to perform side effects in function components. Side effects can be anything that reaches outside the component to interact with the outside world, such as data fetching, subscriptions, or manually changing the DOM. useEffect is designed to unify various lifecycle features that were previously split in class components into componentDidMount, componentDidUpdate, and componentWillUnmount.

Figure 1: useEffect visual explanation

Development Needs for useEffect

Managing side effects in React components is essential for interacting with non-local systems, like a web API or browser’s storage. Prior to hooks, these operations were spread across different lifecycle methods in class components, which could lead to redundancy and complexity. useEffect consolidates these operations into a single API, making it easier to follow and maintain the flow of side effects relative to component rendering and state changes.

Figure 2: structure of useEffect hook
import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0); // Initializing state variable 'count'

useEffect(() => {
// Side effect function
console.log("The count is:", count); // Logs the current count

// Cleanup return function
return () => {
console.log("I am being cleaned up!"); // Cleanup code that runs on component unmount or before the effect runs again
}
}, [count]); // Dependency array containing 'count'

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
decrement
</button>
</div>
);
}

export default Counter;
  • The useEffect hook here is used to perform side effects in the component. The side effect in this case is a simple console.log statement that outputs the current value of count whenever it changes.
  • The dependency array [count] at the end of the useEffect call tells React to only re-run the side effects if the value of count changes. This is crucial for performance optimization, as it prevents the side effects from running on every re-render, instead only executing when necessary.
  • The function returned within the useEffect is a cleanup function. Cleanup functions are useful for various purposes such as clearing timers, canceling network requests, or removing event listeners when a component is about to re-render or unmount. In this example, it logs a message to the console, demonstrating when the cleanup process occurs.

Example:

Let’s consider a scenario where we fetch data from an API and display it:

import { useState, useEffect } from 'react';

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

useEffect(() => {
const fetchData = async () => {
const response = await fetch('https://api.example.com/users');
const data = await response.json();
setUsers(data);
};

fetchData();
}, []); // The empty array makes sure the effect runs only once after the initial render

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

export default UserList;

In this example, useEffect is used for data fetching. The empty dependency array [] tells React to run the effect only once after the initial render, mimicking the behavior of componentDidMount in class components. This pattern is essential for avoiding unnecessary network requests on every component update.

How the Frontend Development Became Easier After the useEffect

useEffect has greatly simplified handling side effects in React applications:

  • ♻️ Consolidation of Lifecycle Methods: It merges the capabilities of multiple lifecycle methods into one API, reducing complexity and potential for bugs.
  • 🚀 Optimized Performance: It helps prevent performance issues by managing when side effects run, and it can be configured to skip effects if certain values haven’t changed.

As we have seen, useEffect is a powerful tool for managing side effects in your React components, ensuring that your UI and your side effects are properly synchronized.

I appreciate you taking the time to read this article.🙌

🔔 Stay tuned for the next article in this series, where we will explore useMemo and how it optimizes performance by memorizing expensive calculations.

Before you move on to explore next article, don’t forget to give your claps 👏 for this article and leave your feedback💭 on the comment section.
Stay connected with me on social media. Thanks for your support and have a great rest of your day! 🎊

Part 1: useState — https://medium.com/@imvinojanv/exploring-react-hooks-a-comprehensive-tutorial-series-part-1-usestate-3c1ce8378e95

✍️
Vinojan Veerapathirathasan.
LinkedIn : https://www.linkedin.com/in/imvinojanv/
Email: imvinojanv@gmail.com

--

--

Vinojan Veerapathirathasan

Software Engineer at EL | Designer | Medium Writer | AI Enthusiast | Entrepreneur | Specializing in Modern Web Application Development