Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

99
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda