Understanding React useEffect Hook
By Amirul Adham
•
November 10, 2025
ReactJavaScriptFrontend
Understanding React useEffect Hook
The useEffect hook is one of the most important hooks in React. It allows you to perform side effects in functional components.
Basic Syntax
useEffect(() => {
// Side effect code here
console.log("Component mounted or dependencies changed");
// Cleanup function (optional)
return () => {
console.log("Cleanup before effect runs again or on unmount");
};
}, [dependencies]); // Dependency array
The Dependency Array
The dependency array controls when the effect runs:
No dependency array
useEffect(() => {
console.log("Runs after every render");
});
Empty dependency array
useEffect(() => {
console.log("Runs only on mount");
}, []);
With dependencies
useEffect(() => {
console.log("Runs when count changes");
}, [count]);
Common Patterns
Fetching Data
useEffect(() => {
const fetchData = async () => {
const response = await fetch("/api/data");
const data = await response.json();
setData(data);
};
fetchData();
}, []);
Cleaning Up Subscriptions
useEffect(() => {
const subscription = observable.subscribe((value) => {
setValue(value);
});
return () => subscription.unsubscribe();
}, []);
Key Takeaways
- ✅ Use
useEffectfor side effects like fetching data or subscribing - ✅ Always include the dependency array
- ✅ Return a cleanup function when needed
- ✅ Be careful with infinite loops - make sure dependencies are correct
Happy coding! 🎉
About the Author
Amirul Adham is a full-stack developer and technical writer passionate about building fast, modern web applications and sharing knowledge with the developer community.