React useEffect Hook for handling side effects like data fetching, subscriptions, and manual DOM manipulations
useEffect is used for handling side effects like data fetching, subscriptions, timers, etc.
Fetch user data when component mounts (empty dependency array [])
Create a timer with useEffect and clean it up on unmount
Re-fetch user data when user ID changes
Select User ID:
// 1️⃣ Basic Usage - Run only on mount
useEffect(() => {
fetchData();
}, []); // Empty array = Run once only
// 2️⃣ With Cleanup Function - Timer/Subscription
useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1);
}, 1000);
// 🧹 Cleanup function
return () => clearInterval(timer);
}, []);
// 3️⃣ Watch Dependency Changes
useEffect(() => {
fetchUser(userId);
}, [userId]); // Re-run when userId changes
// 4️⃣ Async Operations (Recommended Approach)
useEffect(() => {
const fetchData = async () => {
const result = await api.getData();
setData(result);
};
fetchData();
}, []);