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…
>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");
}, []);