'Uncaught Error: Too many re-renders. After setting useState value

The error: Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. occurred after...

I changed my code from this:

if(location.state.name !== undefined || location.state.Username !== undefined){
  console.log(location.state.name);
} else{
  console.log("Nothing");
}

to this:

if(location.state.name !== undefined || location.state.Username !== undefined){
  setName(location.state.name);
} else{
  console.log("Nothing");
}

Where name, setName are empty useState string, and after setting name value as location.state.name which is a string that contains a username.



Solution 1:[1]

It sounds like you've got this logic running on render, and you're rendering the state variable name, which is causing an infinite loop. You're setting state with setName(location.state.name), and when you set state you trigger a re-render of the component. Then on re-render, it's re-running this logic, setting the state, which triggers a re-render.....

If you only want to do this code once on page render, it needs to be inside a useEffect hook with no args (for functional component):

useEffect( () => {
  if (location.state.name !== undefined) {
    setName(location.state.name);
  } else {
    console.log("Nothing");
  }), [] );

or in a componentDidMount() (for class component):

componentDidMount() {
 //your same logic
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Jones