React Query with hooks is throwing error, “Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.”

Tags: , , ,



I am working on a React JS project that is using React query, https://react-query.tanstack.com/, React hooks and functional components. But it is throwing error when I use react query for API call.

This is my component and how I use query within it.

const App = () => {
   const [ list, updateList ] = useState([])
   const info = useQuery(["item-list"], getList, {
    retry: false,
    refetchOnWindowFocus: false,
  })

  if (info.status == "success") {
     updateList(info.data)
  }
    return (
       //view components here
    )
}

This is my getList API call logic

export const getList= async () => {
  const { data } = await api.get("8143487a-3f2a-43ba-b9d4-63004c4e43ea");
  return data;
}

When I run my code, I get the following error:

react-dom.development.js:14815 Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

What is wrong with my code?

Answer

The main reason of that error here is you are running that code block in the if statement in an infinite loop once you have info.status === 'success' as true. Then in every render the updateList is called which triggers an another render.

Probably I would use useEffect hook here in order to listen for changes at info as:

useEffect(() => {
  if (info.status == "success") {
     updateList(info.data)
  }
}, [info])

You should remove that if statement from the body of <App /> component and use the useEffect hook instead as suggested above. By doing this that if statement will be checked once info is changing and not on every render.

Suggested read is Using the Effect Hook.



Source: stackoverflow