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

221
Views
reactjs Avoid Infinite loop using the useState and useEffect

How to avoid infinite loop? I mean in the first click the StudentSubject must be undefined, and in the second click it will get the data, in my current code the result are infinite loop, it keeps looping the console.log(getStudentId, getRelevance) how to avoid that?

  const [getStudentId, setStudentId]= useState();
  const [getRelevance, setRelevance]= useState();

  useEffect(() => {
    student();
  }, []);
  
  const onClickGrade = (studentId, relevance) => {

   .....
    console.log(getStudentId, getRelevance) //undefined
    if(StudentSubject === undefined){
        onClickGrade(studentId, relevance) //infinite loop
    }
   ....
  }

  const student = () => {
    .....
    view.on('click', onClickMap);
    .....
  }

  const onClickStudent = (event)=>{
      const studentId = student.getAttribute('id');
      const relevance = student.getAttribute('relevance');
      setStudentId(studentId)
      setRelevance(relevance)
      onClickGrade(studentId, relevance)
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are recursively calling onClickGrade

const onClickGrade = (studentId, relevance) => {

   .....
        onClickGrade(studentId, relevance) ## Infinite loop in a recursive call
   ....
  }

It depends on what you wants to achieve but you certainly need to change your logic or at least add a condition to prevent an infinite loop in recursion! Your studentSubject sounds to stay always undefined. You might need to save prevStudentSubject and compare that with the current subject.

if (studnetSubject === prevStendentSubject) return
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!