const [products, setProducts] = useState([]);
const [displayProduct, setDisplayProduct] = useState([])
useEffect(() => {
fetch('http://localhost:5000/products')
.then(res => res.json())
.then(data => {
setProducts(data)
setDisplayProduct(data)
console.log(data);
})
})
const handleSearch = (e) => {
const searchText = e.target.value;
const matchedProduct = products?.filter((data) =>
data.name.toLowerCase().includes(searchText?.toLowerCase())
);
setDisplayProduct(matchedProduct);
console.log(searchText);
console.log(matchedProduct);
};
console.log(products);[here you can see always increasing ][1]
[1]: https://i.stack.imgur.com/FOeaM.png
Asked
Active
Viewed 40 times
0

Shubham Dixit
- 9,242
- 4
- 27
- 46
-
1possible duplicate: https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect – about14sheep Jan 02 '22 at 17:01
1 Answers
3
You are calling the api again and again after making change in your state ,as useEffect
is called as an sideEffect after every state change ,so it creates an infinite loop
useEffect(() => {
fetch('http://localhost:5000/products')
.then(res => res.json())
.then(data => {
setProducts(data)
setDisplayProduct(data)
console.log(data);
})
},[])
Pass an empty array in the useEffect
.It will call the useEffect only once when your page loads for the first time
See this answer -React Hooks - 0 vs. empty array as second argument in useEffect

Shubham Dixit
- 9,242
- 4
- 27
- 46