Click here to Skip to main content
15,905,679 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,

I have an error with my React app:
JavaScript
<pre>index.js:1 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.
    in App (at src/index.js:8)
    in StrictMode (at src/index.js:7)

My code is in my GitHub repo. The file where the error occured is in my App.js file. Scroll down, and the error is where the // Save to Load section is.

Please help, thank you!

What I have tried:

Searching on StackOverflow, CodeProject, and on the web and tried to fix it myself but couldn't find anything that solved my problem.
Posted
Updated 5-Nov-20 23:58pm
v4
Comments
Sandeep Mewara 21-Sep-20 10:15am    
You need to share the code, specifically the line raising the error.

Or else the answer to your query is already shared: "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."
h311o 21-Sep-20 23:15pm    
Sorry, I forgot 😊

I updated my question just now.

EDIT: Right, now I know why the error is occuring. I used 2 useEffects() functions, but I need both of them. How do I use both without causing an error?

1 solution

Yes! I solved this problem! It was because of the useEffect(), but it wasn't because it was being used twice.

The problem was because I didn't add an empty array to my useEffect() function so that it would have only run once:

JavaScript
// Save to Load
  const saveLocalTodos = () => {
    localStorage.setItem("todos", JSON.stringify(todos));
  };
  const getLocalTodo = () => {
    if (localStorage.getItem("todos") === null) {
      localStorage.setItem("todos", JSON.stringify([]));
    } else {
      let todoLocal = JSON.parse(localStorage.getItem("todos"));
      setTodos(todoLocal);
    }
  };
  useEffect(() => {
    getLocalTodo();
  }, []);


But thanks @SandeepMewara for your help! 😃
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900