Fetching Based on Props or State
What you'll learn: How to make useEffect re-fetch data automatically whenever dynamic values like search terms, IDs, or filters change.
The Core Idea
So far, you've seen fetching with an empty dependency array [], which runs once on mount. But what if you need to fetch different data based on user input or changing props? The solution is simple: include those dynamic values in the dependency array. Whenever they change, useEffect re-runs and re-fetches.
Think of it like a vending machine that watches your selection button. Every time you press a different button (the dependency changes), it fetches a different snack. Same machine, different input, different result.
How It Works
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
});
}, [userId]); // Re-fetch whenever userId changes
if (loading) return <div>Loading...</div>;
return <div>{user.name}</div>;
}
When userId changes (maybe from routing or parent state), useEffect sees the dependency change and re-runs the fetch. Same pattern works for search queries, filter options, page numbers—anything that determines which data to fetch.
Why This Matters
Without including these values in the dependency array, your component would show stale data. If userId changed from 5 to 10, you'd still be showing user 5's data. By adding [userId], React automatically synchronizes your fetched data with the current prop or state.
Key Takeaway: Include any prop or state value that determines what data to fetch in your useEffect dependency array—React will automatically re-fetch when those values change.