๐ Understanding useEffect in React โ A Complete Guide for Beginners

React is one of the most popular JavaScript libraries for building user interfaces, and one of its most powerful hooks is useEffect
. If you're new to React or you've been using useEffect
without fully understanding it, this guide is for you.
๐ What is useEffect
?
In simple terms, useEffect
is a side-effect handler. Side effects are operations that interact with the outside world or impact something outside the scope of the function, such as:
Fetching data from an API
Manipulating the DOM
Subscribing to events or timers
jsxCopyEditimport { useEffect } from "react";
useEffect(() => {
console.log("Component mounted");
}, []);
The function above runs once when the component mounts, similar to componentDidMount
in class components.
๐ Dependency Array Explained
The second parameter of useEffect
is the dependency array, and it controls when the effect should run:
[]
: Runs only on mount.[count]
: Runs whencount
changes.No array: Runs on every render.
jsxCopyEdituseEffect(() => {
console.log("Count changed:", count);
}, [count]);
This is super helpful when you want to react to state or props changes.
๐ฅ Common Mistakes
1. Forgetting the dependency array
jsxCopyEdituseEffect(() => {
// Runs on every render โ may cause performance issues
});
2. Using state setters inside useEffect
without care
This may cause infinite loops:
jsxCopyEdituseEffect(() => {
setCount(count + 1); // โ ๏ธ Infinite loop!
}, [count]);
๐งน Cleanup Function
useEffect
can return a cleanup function that runs when the component unmounts or before the effect runs again:
jsxCopyEdituseEffect(() => {
const timer = setInterval(() => {
console.log("Tick");
}, 1000);
return () => {
clearInterval(timer); // cleanup
};
}, []);
๐ Real Use Case: Fetching Data
jsxCopyEditimport { useEffect, useState } from "react";
const Posts = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then((data) => setPosts(data));
}, []);
return (
<div>
{posts.map((post) => (
<p key={post.id}>{post.title}</p>
))}
</div>
);
};
โ
When to Use useEffect
Use it when:
You need to fetch or sync data
You need to interact with browser APIs (like localStorage)
You set up event listeners or timers
๐ง Summary
useEffect
runs side effects in functional componentsAlways manage dependencies carefully
Clean up to avoid memory leaks
Think of
useEffect
as a combination of lifecycle methods
๐ฃ Bonus Tip: Break large useEffect
functions into smaller, focused effects for better maintainability.
Subscribe to my newsletter
Read articles from Noura Mostafa directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Noura Mostafa
Noura Mostafa
๐ Aspiring Full-Stack Developer Blogger ๐จโ๐ป Passionate about web development and coding. โ๏ธ Sharing my journey through tech via CodeOdyssey ๐ "The code is a journey, not a destination."