The useEffect hook handles side effects like data fetching, subscriptions, timers, and DOM mutations.
⊞Code Example
import React, { useState, useEffect } from 'react';
export default function UserDataFetcher({ username }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let isCancelled = false;
setLoading(true);
fetch(`https://api.github.com/users/${username}`)
.then(res => res.json())
.then(data => {
if (!isCancelled) {
setUser(data);
setLoading(false);
}
});
return () => {
isCancelled = true; // Cleanup on unmount or username change
};
}, [username]);
if (loading) return <p className="text-slate-400">Loading user profile...</p>;
return <div className="text-white font-bold">{user?.name} ({user?.public_repos} Repos)</div>;
}
