Home > Blockchain >  Uncaught Error: Maximum update depth exceeded error with useState()
Uncaught Error: Maximum update depth exceeded error with useState()

Time:07-11

Why am I getting this error?

Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.**

This is my code:

const [roles, setRoles] = useState([]);

useLayoutEffect(() => {
  setRoles(["5nxg5wvb"]);
});

Note that the same error appears when I use useEffect, and that error only goes away when I change the code to this:

useLayoutEffect(() => {
  setRoles("5nxg5wvb");
});

Any help would be appreciated...

CodePudding user response:

You need to provide a dependency array in setEffect or it will run on every state change. Since it's changing state, that means it will run, which causes it to run again, which causes it to run again, etc...

The dependency array tells it when to run. An empty array means "run this effect on mount," so it will run only once. An array with variable names in it means, "run when any of these variables change."

useLayoutEffect(() => {
  setRoles("5nxg5wvb");
}, []);

CodePudding user response:

Why did this error occur?

Because you are using useEffect or useLayoutEffect while you don't specify the second params of the hooks, you only put the first param which is the callback function, and the state value is always different.

Why does putting this ["5nxg5wvb"] doesn't work while putting "5nxg5wvb" works?

  1. Because if you use [] (an array), you create a new object and compare it with the previous object every time it re-renders (because you don't specify the second params of the hooks, but do know that [] === [] will result in false value)
  2. While if you use "" (a string), React will directly compare the value instead, and if it's the same, the state won't be updated and there will be no re-rendering.

How to fix this?

  1. You can put the second param of the hooks like this, the code below will make the hooks run only once:
useLayoutEffect(() => {
  setRoles(["5nxg5wvb"]);
}, []);
  1. Just put the new value directly to the useState like this, there is no need to put useEffect with static data:
const [roles, setRoles] = useState(["5nxg5wvb"]);

If both suggestions don't work for your use case, please do put more info about your use case.

  • Related