Home > Software design >  How do I resolve Uncaught Error: Too many re-renders. React limits the number of renders to prevent
How do I resolve Uncaught Error: Too many re-renders. React limits the number of renders to prevent

Time:07-15

I am getting an object location from another page like this.

const location = useLocation();

I am trying to set a variable like this.

if (location.state !== null) {
  console.log(location.state.name.companyName)
  setcompanyOneAlready(location.state.name.companyName);
  console.log(companyOneAlready);
}

But this results in a "Too many renders" error. I realize it's because of the way I am setting companyOneAlready but I don't know how to correct this. Any help is appreciated.

CodePudding user response:

It seems you are running the code as an unintentional side effect and the condition is malformed.

Use the useEffect hook with correct dependencies to issue the side-effect to update state.

Example:

useEffect(() => {
  if (location.state !== null) {
    setcompanyOneAlready(location.state.name.companyName);
  }
}, [location.state]);

To help save a rerender you can also check the current companyOneAlready value prior to enqueueing the state update.

useEffect(() => {
  if (location.state?.name?.companyName !== companyOneAlready) {
    setcompanyOneAlready(location.state.name.companyName);
  }
}, [location.state, companyOneAlready]);

CodePudding user response:

It seems like location.state is never null. I believe by default it is an empty object and {} !== null is always true. Also, I assume that setcompanyOneAlready changes the state in the component. That triggers rerender and your's condition will be true on every render. That's the reason why you get the mentioned error.

You should put this condition inside useEffect and useEffect should have a name or companyName in the dependency array to rerun the effect only when some of these values are changed.

  • Related