Fetching Data on Mount and Update
0 541
🌐 Introduction: Why Fetch Data in React?
In modern React apps, fetching data from an API is a common task. Whether you’re building a weather app, a blog, or a dashboard, you’ll need to load external data when your component mounts or updates. React’s useEffect hook makes this process seamless and efficient.
🔁 useEffect: The Core Hook for Fetching
The useEffect hook runs after the component renders. It’s perfect for running side effects like fetching data. You can configure it to run only once on mount or every time specific state/props change.
📥 Fetching Data on Mount (Initial Load)
This is the most common pattern. You want to fetch data once when the component is first displayed. Just pass an empty dependency array [] to useEffect:
import { useEffect, useState } from "react";
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []); // empty array = run only once
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Why this works: The effect runs only once after the initial render — ideal for API calls or one-time setup logic.
🔄 Fetching Data on Update (State or Prop Change)
Sometimes you want to re-fetch data when a user changes a filter, selects a different tab, or updates input. For this, include the triggering variable in the dependency array.
function SearchUser({ searchTerm }) {
const [results, setResults] = useState([]);
useEffect(() => {
if (!searchTerm) return;
fetch(`https://api.example.com/search?q=${searchTerm}`)
.then(res => res.json())
.then(data => setResults(data));
}, [searchTerm]); // fetch when searchTerm changes
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Tip: Always check for empty or invalid values before firing a new request.
🔐 Adding Loading and Error States
For better UX, add loading and error feedback. Here's how to structure it:
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
setError(null);
fetch("https://api.example.com/data")
.then(res => {
if (!res.ok) throw new Error("Network error");
return res.json();
})
.then(data => setData(data))
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, []);
Now you can display:
- Loading spinner while fetching
- Error message if something fails
- Data list if everything works
⚠️ Best Practices for Data Fetching
- 📌 Always include a dependency array in
useEffect. - 📌 Use cleanup functions if you’re fetching repeatedly or using intervals.
- 📌 Cancel fetches if the component unmounts early (e.g., using
AbortController). - 📌 Avoid calling fetch without condition checks — it can cause unnecessary network usage.
🚀 Final Thoughts
Fetching data on mount and update is a core feature in any dynamic React app. With useEffect, it becomes predictable and powerful. Whether you're building a product list, search feature, or real-time dashboard, mastering this pattern helps you deliver responsive and data-driven UIs. Keep it clean, handle loading and errors, and fetch smartly! 🌐⚙️
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments