Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda