A super cool feature of React Query is that we can auto refetch on a specified interval.
This could be useful if you quickly change data that needs to be rechecked every minute.
In our example, we’ll call a random API endpoint, meaning every request has new data, and showcase whatever is in that refetch.
It will look like this:
Using auto refetching in React Query
To use the auto refetch mode, you can pass an optional parameter to the React Query hook called refetchInterval
. The value is in milliseconds.
const { isLoading, data } = useQuery(
'vehicle',
async () => {
const { data } = await axios.get(
'https://random-data-api.com/api/vehicle/random_vehicle'
);
return data;
},
{
refetchInterval: 6000,
}
);
The above example will query the random data API and ask for a random vehicle. This call will refetch the data every 6000 milliseconds.
When implementing code like this, be aware that this can be heavy on your API, and one should be wise about when to use this approach.
Other refetching options
React Query comes with more of these refetch functions that we can leverage.
By default, it will auto refetch every time the window focuses, for instance, let’s take a look at what other options there are:
refetchInterval
: See the above examplerefetchIntervalInBackground
: When set to true, the above function will even call when the tab is in the backgroundrefetchOnMount
: You can set this to false to don’t do the initial mount loadingrefetchOnWindowFocus
: Will refetch every time the window focus is set. You can set this to falserefetchOnReconnect
: Will refetch once a connection has been remade
Between all of these, you can mix when data should be loaded.
You can try the refetch out in this Sandbox.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter