Reputation: 13
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...
Upvotes: 0
Views: 135
Reputation: 1048
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.
["5nxg5wvb"]
doesn't work while putting "5nxg5wvb"
works?[]
(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)""
(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.useLayoutEffect(() => {
setRoles(["5nxg5wvb"]);
}, []);
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.
Upvotes: 0
Reputation: 5303
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");
}, []);
Upvotes: 1