
Category:Mern Stack
Tags:
JavaScriptJSMern StackNext.jsReactuseEffect hook
Published:May 6, 2025
πΉ React Hook Deep Dive: useEffect Made Simple
Our format stays strong:
- β Core Concept
- π Real Example
- π§ Best Practices
- β οΈ Pitfalls to Avoid
- π Execution Order
- π§ͺ Optional Demo (CodeSandbox or Timeline)
β 1. Concept
useEffect
lets you perform side effects in function components β like data fetching, subscriptions, DOM updates, or timers.
It runs after render, and can optionally clean up.
useEffect(() => {
// run side effect
return () => {
// optional cleanup
};
}, [dependencies]);
π 2. Example: Fetching Data on Mount
import React, { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []); // empty array = run once on mount
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
This runs once after initial render and fetches user data.
π§ 3. Best Practices
- β
Use multiple
useEffect
s for unrelated concerns - β Always define dependencies correctly
- β Return a cleanup function if needed (like removing event listeners)
- β Use async functions inside the effect, not at the top level
useEffect(() => {
const load = async () => {
const res = await fetch(...);
const data = await res.json();
setData(data);
};
load();
}, []);
β οΈ 4. Common Pitfalls
- β Forgetting dependencies β stale state or bugs
- β Using async directly in
useEffect
(it returns a promise, not a cleanup) - β Not cleaning up subscriptions β memory leaks
π 5. Execution Order
Step | Phase | What Happens |
---|---|---|
1 | Render | Component mounts |
2 | Commit | DOM updates |
3 | Post-render | useEffect runs |
4 | Re-render | Runs again if deps changed |
5 | Unmount | Cleanup (if defined) runs |
β Previous Post: How to Configure SMTP in Joomla: Step-by-Step Guide for Reliable DeliveryNext Post: Letβs now learn React Hooks in this structured way β
Comments (0)
No comments yet. Be the first to comment!