Why is useQuery making my component re-render when I come back to the tab?

0

Issue

I’m using react-query library, and I looked it up, and useQuery can make your react component re-render because it has states, but the weird thing is that it re-renders when I change tabs (like, I go to youtube, then come back to my app and the component just re-renders). But it only happens with useQuery, and I don’t understand why.

Edit: It also happens when I click my console and then click the app again

The code is very simple:

const { data } = useQuery("pokemon", () =>
    axios("https://pokeapi.co/api/v2/pokemon/")
);
console.log(data);

It’s literally happening right now. Every time I go back to my app, it just logs the data again. I don’t know what I’m missing

Solution

If you’re using the react-query library, consider setting the refetchOnWindowFocus option to false

So your code should look like this

const { data } = useQuery("pokemon", () =>
    axios("https://pokeapi.co/api/v2/pokemon/"), 
    {
      refetchOnWindowFocus: false
    }
);
console.log(data);

You can also set a refetchInterval option in milliseconds to only refetch at certain time intervals

Answered By – fortunee

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More