I'm building a React app where I fetch data from an API and update the state. However, I'm facing a bug related to useEffect
dependencies, which is causing an infinite re-render loop. Here's the relevant code:
import React, { useEffect, useState } from 'react';
const DataComponent = () => {
const [data, setData] = useState([]);
const [search, setSearch] = useState('');
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(`http://localhost:5000/data?q=${search}`);
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, [search, data]);
return (
<div>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search..."
/>
<ul>
{data.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
</div>
);
};
export default DataComponent;
Problem:
What I've Tried:
fetchData
function outside useEffect
, but it didn’t resolve the issue.useRef
to store the previous state, but the issue persisted.Questions:
I’ve looked at the React docs and other answers, but none specifically address this combination of async functions and dependency handling in useEffect
. Any insights or solutions would be greatly appreciated!
Responses to your questions:
useEffect
detects that data
changes value at each setData
, meaning: the value of result
is either an object or a different value (string, number). And because you have set data
to be a dependency.fetchData
on if data has been fetched already. const fetchData = async () => {
try {
const response = await fetch(`http://localhost:5000/data?q=${search}`);
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
}
};
useEffect(() => {
if (!data) fetchData();
}, [search, data]);