Skip to content
Advertisement

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.

Advertisement

Answer

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.

In fact, if you use callback in setState like blew eslint never complain about the list in the dependency array. so you can safely remove the list from useEffect dependency array.

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement