I have this useEffect hook and few buttons which perform a specific task all the buttons are perfectly working but the clear btn is causing infinite warning.
this is the warning
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn’t have a dependency array, or one of the dependencies changes on every render.
I am creating a todo list app as I am a beginner in react i am practising this project on my own here is the code
let finalArr = arr;
const [renderAgain, setRenderAgain] = useState(() => returnTodos(finalArr));
useEffect(() => {
if (btn === "clr") {
deleteCompleted();
} else if (btn === "act") {
finalArr = findUniqueElements(arr, finishArr);
} else if (btn === "com") {
finalArr = finishArr;
} else {
console.log("all");
finalArr = arr;
}
const newRenderAgain = returnTodos(finalArr);
setRenderAgain(newRenderAgain);
}, [arr, finishArr, btn]);
function deleteCompleted() {
finalArr = findUniqueElements(arr, finishArr);
setArr(finalArr);
setFinishArr([]);
}
my GitHub repo link: https://github.com/ayussh-2/React-To-do-list
just fix these problems
2
Answers
when btn === "clr", your useEffect calls deleteCompleted, which change arr and finishArr with
setArr(finalArr);
andsetFinishArr([]);
, and since arr and finishArr are dependencies in your useEffect, the useEffect will run again, and repeats infinitely.A quick workaround is to reset btn.
Also this line
const [renderAgain, setRenderAgain] = useState(() => returnTodos(finalArr));
should beconst [renderAgain, setRenderAgain] = useState(returnTodos(finalArr));
based on what you have in your useEffectYour useEffect seems to only depend on the state of the btn variable. Try having it as the only dependency in the useEffect Array.
This way it will only re-run when the btn variable changes.