The Complete Abort Pattern in One Example
You'll learn: How to write a complete, production-ready fetch in useEffect with cleanup, abort handling, loading states, and error management—all in one cohesive pattern.
The Full Picture
You've learned all the pieces individually. Now let's see how they work together in a real component that fetches data safely:
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(response => {
if (!response.ok) throw new Error('Failed to fetch');
return response.json();
})
.then(data => {
setUser(data);
setLoading(false);
})
.catch(err => {
if (err.name !== 'AbortError') {
setError(err.message);
setLoading(false);
}
// AbortError is silently ignored
});
return () => controller.abort();
}, [userId]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <div>{user?.name}</div>;
}
Why This Pattern is Complete
- AbortController prevents race conditions when
userIdchanges - Cleanup function aborts in-flight requests on unmount or re-run
- Error handling distinguishes AbortError from real failures
- Loading state resets when a new fetch starts
- Error state clears when retrying
Think of it like a delivery service: when you change your order (new userId), the driver turns around immediately (abort), and you reset the "order status" board (loading/error states) for the new delivery.
Key Takeaway: This pattern combines AbortController cleanup, state management, and error filtering to handle all real-world fetch scenarios safely—use it as your go-to template for data fetching in effects.