π React Functional Lifecycle using useEffect β Complete Guide (2025)
π§² Introduction β Functional Lifecycle with useEffect
In class components, React used explicit lifecycle methods like componentDidMount and componentDidUpdate. In functional components, these lifecycle behaviors are implemented using the powerful useEffect hook.
With useEffect, you can handle:
- π§± Mounting (
componentDidMount) - π Updating (
componentDidUpdate) - π§Ή Cleanup (
componentWillUnmount)
π― In this guide, youβll learn:
- How to simulate lifecycle methods with
useEffect - How the dependency array controls behavior
- Examples for API calls, timers, subscriptions
- Best practices for functional lifecycle logic
π§© What is useEffect?
useEffect is a React Hook that runs side effects in functional components β such as:
- Fetching data
- Subscribing to events
- Setting intervals
- Manipulating the DOM
β Syntax:
useEffect(() => {
// side effect logic
return () => {
// cleanup (optional)
};
}, [dependencies]);
π§± 1. Simulating componentDidMount β Run Once on Mount
useEffect(() => {
console.log('Mounted once');
}, []);
β
The empty dependency array [] ensures the effect runs only once, after the first render β perfect for:
- API requests
- Event listeners
- Analytics
π 2. Simulating componentDidUpdate β Run on State or Props Change
useEffect(() => {
console.log('Count changed to:', count);
}, [count]);
β
This effect runs every time count changes, allowing you to:
- React to prop changes
- Re-run logic when state updates
- Trigger conditional side effects
π§Ή 3. Simulating componentWillUnmount β Cleanup Logic
useEffect(() => {
const timer = setInterval(() => {
console.log('Interval tick');
}, 1000);
return () => {
clearInterval(timer);
console.log('Component unmounted');
};
}, []);
β The returned function acts as a cleanup function β called:
- Before component unmounts
- Before re-running the effect (when dependencies change)
π Lifecycle Summary with useEffect
| Class Lifecycle | Functional Equivalent |
|---|---|
componentDidMount() | useEffect(() => { ... }, []) |
componentDidUpdate() | useEffect(() => { ... }, [dep]) |
componentWillUnmount() | useEffect(() => { return () => {...} }, []) |
π Example β Fetching Data on Mount
import { useState, useEffect } from 'react';
function UserProfile({ id }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/user/${id}`)
.then(res => res.json())
.then(setUser);
}, [id]);
return <div>{user?.name}</div>;
}
π Fetches data when id changes, and re-runs only if needed
β±οΈ Example β Timer with Cleanup
useEffect(() => {
const interval = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(interval);
}, []);
β Runs once on mount and clears interval on unmount
β οΈ Common Pitfalls
| Mistake | Fix |
|---|---|
| Forgetting dependency array | Effect runs on every render |
| Omitting dependencies | May cause stale or incorrect behavior |
| Performing async logic improperly | Wrap async logic in an IIFE |
| Missing cleanup | Can lead to memory leaks |
π Best Practices
β
Use multiple useEffect calls for unrelated logic
β
Always include all dependencies in the array
β
Use cleanup for subscriptions, intervals, and event listeners
β
Avoid putting effects inside conditionals or loops
β
Use useRef to track mounts, previous values, or internal state
π Summary β Recap & Next Steps
The useEffect hook replaces class lifecycle methods in functional components. With proper use of the dependency array and cleanup, it offers powerful, clean, and flexible lifecycle management.
π Key Takeaways:
useEffecthandles mounting, updating, and unmounting- Control effect behavior with dependency arrays
- Cleanup with return function to mimic
componentWillUnmount - Combine multiple
useEffectcalls to separate concerns
βοΈ Real-World Relevance:
From fetching user data to setting up real-time subscriptions, useEffect is used in nearly every modern React component.
β FAQ Section
β Does useEffect run after every render?
β
Only if you omit the dependency array. Otherwise, it depends on what values you list in [deps].
β How do I replicate componentWillUnmount in functional components?
β
Use the return statement in useEffect:
useEffect(() => {
return () => {
console.log('Cleanup');
};
}, []);
β Can I use multiple useEffect() hooks in one component?
β
Yes! Itβs a best practice to separate effects by concern.
β Can useEffect be async?
β No, but you can define an async function inside:
useEffect(() => {
(async () => {
await fetchData();
})();
}, []);
β What if I forget a dependency?
β οΈ Your effect might use stale values. Use eslint-plugin-react-hooks to catch missing dependencies.
Share Now :
