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

108
Views
React: infinite loop even though useEffect should detect change and prevent loop
const [label, setLabel] = useState([<>, <>]);
const [labelType, setLabelType] = useState('none');

 useEffect( () => {
   if (props.label === 'label1') { 
      setLabel([<div>...</div>, <div>...</div>])
   }
   if (props.label=== 'label2') {
      setLabel([<div>...</div>, <div>...</div>]);
   }
   if (props.label === 'label3') {
      setLabel([<div>...</div>, <div>...</div>])
   }
}, [labelType] );

setLabelType(props.label)

return (
    <div className=''>
        <div id=''>{label}</div>
    </div>
)

So I'm basically passing in a prop and just trying to use that value to decide what to set my {label} to and the initial value of props.label is 'label1'. If my console logs, I see that 'none' is changed to 'label1' by setLabelType(props.label) and my understanding is that since setLabelType() was used, the stated is updated/ component re-rendered and plus labelType specifically is changed then useEffect() is triggered and the appropriate branch/setLabel() is called based on props. Next render useEffect() is not called since 'label1' -> 'label1' is no change (vs. first time 'none' -> 'label1').

But reality is that I have an infinite loop instead, could anyone explain to me why? I think maybe I need to have setLabelType(props.label) in a function but the trigger for this code to execute is in a different component so there's no 'onChange' prop that would call it in this component (basically when sibling component is clicked, passes data to common parent, parent passes data back down to this child and use the prop to decide render). This seems really simple but I'm confused.

Thanks

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