Here is my Functionality Code. I have tried my best but Can not solved this limitless error. when I check by console log everything is okay. but when I give setProducts it start.
const Header = () => {
const [products, setProducts] = useProducts();
const [searchText, setSearchText] = useState('');`enter code here`
useEffect(() => {
const result = products?.filter(pro => pro.name.toLowerCase().includes(searchText.toLowerCase()));
setProducts(result);
console.log(result);
}, [searchText, products, setProducts]); }
CodePudding user response:
You should move code that is currently in useEffect and put in in useCallback function, and than call that function in useEffect. Right know you are setting products in use effect, and every time you change your products, useEffect triggers again. You can also fix this by removing products from use effect arguments.
CodePudding user response:
Here filter on products is returning an object reference and by updating products using setProducts(result);
which updates products
. which is causing to call useeffect again as 'products' is in dependency list of useEffect. So here is the process:
1- filter products and return new array reference type
2- set this new reference in products and console it
3- react will check dependency array update for useEffect
4- products key is updated so lets run useEffect callback again
5- oh again step 1 and step 2 will cause this loop to run again and
again
try removing products, setProducts from dependency array