skip to Main Content

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


  1. when btn === "clr", your useEffect calls deleteCompleted, which change arr and finishArr with setArr(finalArr); and setFinishArr([]);, 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.

    if (btn === "clr") {
       setBtn('');
       deleteCompleted();
    }
    

    Also this line const [renderAgain, setRenderAgain] = useState(() => returnTodos(finalArr)); should be const [renderAgain, setRenderAgain] = useState(returnTodos(finalArr)); based on what you have in your useEffect

    Login or Signup to reply.
  2. Your useEffect seems to only depend on the state of the btn variable. Try having it as the only dependency in the useEffect Array.

    useEffect(() => {
      // ..your code
    }, [btn]);
    

    This way it will only re-run when the btn variable changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search