Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any help would be appreciated…

>Solution :

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");
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading