I am having an issue with fetching data inside an useEffect(). I can see in the developer tool, that the fetch is called in an infite loop.
I am quite new to React, so maybe this is a simple issue. I have tried looking up others with same issues, but can't seem to make a connection with my code.
Code is below.
export function Category(){
const [categories, setCategories] = useState([]);
useEffect(() => {
fetch('https://localhost:5001/api/Category')
.then(response => response.json())
.then(data =>
setCategories(data));
return () => {
}
})
const renderCategories = (cats) => {
return (
<Table ClassName= "mt-4" striped bordered hoved size= "=sm">
<thead>
<tr>
<th> Id: </th>
<th> Category Name: </th>
<th> Options </th>
</tr>
</thead>
<tbody>
{cats.map(cats=>
<tr key = {cats.categoryId}>
<td> {cats.categoryId}</td>
<td> {cats.name}</td>
</tr>)}
</tbody>
</Table>
)
}
return(
<div>
{renderCategories(categories)}
</div>
)
}
useEffect
is called whenever state
changes. In your code, you call setCategories
inside useEffect
to change the categories
state. That action triggers the useEffect
itself in an infinite loop.
This is a common issue for new people who learn React 17 with hooks or even former React Class developers. To avoid this, using square bracket []
like @Chris G is okay for now but it isn't a good practice when scaling because you just tricks React to runs useEffect
once.
Dan Abramov recommends using useReducer
to manage state outside of useEffect
.
This is his excellent article that explains every corner of useEffect
. Let's pour some coffee and read it because it's as long as a book: https://overreacted.io/a-complete-guide-to-useeffect/