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

518
Views
React : How can i prevent Maximum update depth exceeded from a function beign called in useEffect

I'm getting this error :

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

I have this state :

const [arrayOfDocuments, setArrayOfDocuments] = useState([]);

which store objects of type document

Function which add the docs to the state :

  const pushToArrayOfDocuments = (obj) => {
    if (obj.filename && obj.file && obj.expiredate && obj.doctype) {
      setArrayOfDocuments((oldArr) => {
        const arr = oldArr.slice();
        const index = arr.map((e) => e.filename).indexOf(obj.filename);

        if (index !== -1) {
          arr[index] = obj;
        } else {
          arr.push(obj);
        }

        return arr;
      });
    }
  };

Now this function is beign passed to the sub components :

like this :

<OperatorDocument
  key={`Visura camerale${count}`}
  title="Visura camerale"
  setDocument={pushToArrayOfDocuments}
  description=" in dolor."
  document={getObjectByName('Visura camerale')}
  filedocname="Visura camerale"
 />

Now inside the subcomponent i have this state :

const [file, setFile] = useState(document);

Now if this state changes i call setDocument inside useEffect

  useEffect(() => {
    setDocument(file);
  }, [file, setDocument]);

and now i get the error. Any idea on how can i prevent this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The error already told you the problem because setState is in the array dependency the component updates Everytime.

Try this Delete the setDocument and leave just file in the dependency array that way it updates only when the file changes

Like this [file]

about 4 years ago · Juan Pablo Isaza 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!