Click here to Skip to main content
14,659,429 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi,

I have an error with my React app:
<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, thanks!
- C.B

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 21-Sep-20 22:43pm
v3
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."
CookiBytes 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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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:

// 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! 😃
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100