I am working on a for loop that starts with 1 column at the window.innerHeight of 530px and increments with 1 if the window.innerHeight gets incremented with 40.
This is what I have right now, but it says too many re-renders everytime. Does anyone know why?
let gridcolumns = 1;
useEffect(() => {
for (let i = 530; i < window.innerHeight; i = 40) {
gridcolumns = 1;
}
});
setColumnsAmount(gridcolumns);
CodePudding user response:
You need to add dependency list to your useEffect :
let gridcolumns = 1;
useEffect(() => {
for (let i = 530; i < window.innerHeight; i = 40) {
gridcolumns = 1;
}
setColumnsAmount(gridcolumns);
},[]);
CodePudding user response:
Your useEffect
call has no dependency array, so its callback is called after every render. The callback then does setColumnsAmount
, which triggers a re-render, which triggers the useEffect
callback, which triggers a re-render, etc.
You need to specify a dependency array that says what it is that needs to change to make you want to run the callback, or don't use useEffect
for this at all and do the columnsAmount
change in an event callback (perhaps a resize
event).
Side note: You can probably replace the for
loop with const x = Math.floor(window.innerHeight / 40);
and then doing whatever it is you want to with x
(for instance, you could add it to gridColumns
if that's really the right thing).