❌ How NOT to Fetch API in React (Avoid Infinite Requests)
❌ How NOT to Fetch API in React (Avoid Infinite Requests)
🚨 Common Mistake:
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => setData(data));
}); // ⚠️ No dependency array — runs every render!
This causes the fetch to run on **every re-render**, creating an **infinite loop**!
✅ Correct Way:
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => setData(data));
}, []); // ✅ Empty dependency array = run only once (on mount)
This ensures the fetch runs **only once**, just like `componentDidMount` in class components.
🧠 Extra Tips:
- Use an async function inside `useEffect` if needed.
- Don’t add `data` or `setState` inside the dependency array unless necessary.
- Use proper cleanup (e.g., `AbortController`) for long fetches.
🔒 Example with async/await:
useEffect(() => {
const fetchData = async () => {
const res = await fetch('https://api.example.com/data');
const json = await res.json();
setData(json);
};
fetchData();
}, []);