Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
How do I resolve Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop while setting a state?

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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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]);
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!