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

195
Views
Infinite call to UseEffect UseSelector UseDispatch React.js

Using the getContractsFromAPI action, I get a list of contracts that are in the API, then using useState and renderContracts, I display them on the page, but this starts an endless call to useEffect

const [contracts, setContracts] = useState({});
    

const contractsList = useAppSelector(({ contractsList }) => contractsList);

useEffect(() => {
    dispatch(getContractsFromAPI());
    setContracts(contractsList);
}, [contractsList, dispatch]);

return (
    <div>
        <h2>Contracts:</h2>
        <ul className={styles.contractsList}>{renderContracts(contracts)}</ul>
    </div>
);

How can the problem be solved? I tried to remove [contractsList, dispatch] from useEffect, but then the initial render does not occur when the page is opened

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

0

Put dispatch(getContractsFromAPI()); in it's own useEffect

useEffect(() => {
    setContracts(contractsList);
}, [contractsList, setContracts]);

useEffect(() => {
    dispatch(getContractsFromAPI());
}, [dispatch, getContractsFromAPI]);

you were getting an infinite loop because getContractsFromAPI apparently edit contractsList. The easy solution is having getContractsFromAPI in a useEffect that does not watch for change on contractsList

UPDATE for anyone stumbling upon this answer: the user changed his question, adding more context between the time he posted his question and the time I posted my answer. My answer stays valid, but for the specific use case of @yourBadApple, AKX's answer is more relevant

about 4 years ago · Juan Pablo Isaza Report

0

If you don't really need a shallow copy of the contracts in your component's local state, get rid of the local state and just use them from the selector.

function ContractsComponent() {
  const contracts = useAppSelector(({ contractsList }) => contractsList);

  // Get contracts from API on mount
  useEffect(() => {
    dispatch(getContractsFromAPI());
  }, [dispatch]);

  if (!contracts) return <>Loading...</>;

  return (
    <div>
      <h2>Contracts:</h2>
      <ul className={styles.contractsList}>{renderContracts(contracts)}</ul>
    </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!