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

209
Views
stop infinite loop in useEffect

I got infinite loop running below code, basically I try to sync props's state with local state

const SomeComponent = ({ ids = [] }) => {
  const selectedIds = useStore(reduxStore);

  const [_, setSelectedIds] = useState(selectedIds);

  useEffect(() => {
    setSelectedIds(ids);
  }, [ids]);
};

I can't do if(ids.length) setSelectedIds(ids) because they will be a case where the setSelectedIds is [], I want to sync it too. But I got infinite loop.

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

0

Your problem is you set { ids = [] } with [] as a default value. If you don't pass ids to SomeComponent, it will keep initializing ids as a new fresh array [] that will cause continuous re-renderings

Representing your problem

const { useEffect, useState } = React
const SomeComponent = ({ ids = [] }) => {

  const [_, setSelectedIds] = useState([]);

  useEffect(() => {
    setSelectedIds(ids);
  }, [ids]);
  
  console.log('here')
  
  return null
};

ReactDOM.render(
  <SomeComponent/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

The possible fix is you should set { ids } instead of being with a default value (if it's empty, leave it as it is)

const { useEffect, useState } = React
const SomeComponent = ({ ids }) => {

  const [_, setSelectedIds] = useState([]);

  useEffect(() => {
    setSelectedIds(ids);
  }, [ids]);
  
  console.log('here')
  
  return null
};

ReactDOM.render(
  <SomeComponent/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

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!