r/learnreactjs • u/lifelifebalance • Jun 29 '22
Question Is there an obvious reason that this code throws a "too many re-renders" error?
I can't figure out what is causing this code to throw the error:
let checkedArray = [0,0,0,0,0,0,0,0,0]
const [checked, setChecked] = useState([]);
if(!growth_areas.isLoading){
if(Object.keys(growth_areas).length != 0){
for(let i = 0 ; i < Object.keys(growth_areas).length; i++){
checkedArray[i] = growth_areas[Object.keys(growth_areas)[i]];
}
setChecked(checkedArray);
}For a bit of context, growth_areas is a dictionary loaded in from my database and it contains binary values that I want to set as the state for "checked". The loop sets the values for "checkedArray" using the binary values from the dictionary that was loaded in. This works but as soon as "setChecked(checkedArray)" is called then I get the error.
Can someone see what I'm missing here? Thanks in advance.
Edit: If more code is needed I made a codeshare of the whole file (probably not great code): https://codeshare.io/dwy90M
4
u/____0____0____ Jun 29 '22
You're calling setState directly in the function body under a condition that doesn't change in between calls. Every time setState is called, it triggers a rerender and since your isLoading hasn't changed at all, it immediately calls it again, and again and again. You could add another condition to check if you've done it already. I'm not sure how often you intend for this to run.
2
u/ikeif Jun 29 '22
Is there a useEffect somewhere? Additional logic?
I know sometimes it can say “error at line X” but the problem can be triggered there because of logic elsewhere.