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

97
Views
concatenation state in useEffect cause loop

i had read some questions and article about this issue including this one: but i don't find my answer.

consider this code.

function Component({ page }) {
  
  const [list, setList] = useState([]);
  
  useEffect(() => {
    
    axios.get([url] + page).then(newList => {
      setList([...list, ...newList]);
    });
    
  }, [page, list]);
  
  return ['some jsx for map though list'];
};

i have a pagination and every time i go to next page i need to concatenate the data with previous one, here is the deal.

  • the react complains about dependency array about list and page.

  • i'm agree about page because each time it changes i need to fetch more data. but when i add list to dependency array useEffect find changes in list and fetch more data which cause infinit loop.

i know about hooks but i wonder what is the best practise to solve this issue.

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

0

Your list updates on each page or list dependency update, resulting in an infinite loop. Removing the list argument from the dependency array will fix your bug.

Inside the useEffect, you'd not need list at all..

useEffect(() => {
    
    axios.get([url] + page).then(newList => {
      setList(prev => [...prev, ...newList]);
    });
    
  }, [page]);

Since the method is defined in this component, you'd not even need useCallback hooks to memoize the funtion. And eslint won't throw warnings too

about 4 years ago · Juan Pablo Isaza Report

0

i can not believe this the answer was so simple.

function Component({ page }) {
  
  const [list, setList] = useState([]);
  
  useEffect(() => {
    
    axios.get([url] + page).then(newList => {
      // in this line if you merge two arrays with callback function
      // eslint never complain about the list dependency
      setList(list => [...list, ...newList]); // like this
    });
    
  }, [page]);
  
  return ['some jsx for map though list'];
};
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!