DEV Community

Cover image for Automatically refetching with React Query
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Automatically refetching with React Query

A super cool feature of React Query is that we can auto refetch on a specified interval.

This could be useful if you have quickly changing 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:

Automatically refetching with React Query

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,
  }
);
Enter fullscreen mode Exit fullscreen mode

In the above example, we 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's and one should be very 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 focusses, for instance, let's take a look at what other options there are:

  • refetchInterval: See above example
  • refetchIntervalInBackground: When set to true, the above function will even call when the tab is in the background
  • refetchOnMount: You can set this to false to don't do the initial mount loading
  • refetchOnWindowFocus: Will refetch every time the window focus is set. You can set this to false
  • refetchOnReconnect: 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

Latest comments (2)

Collapse
 
star_trooper profile image
Atharva Shirdhankar

I was searching for this topic from last month . Finally that required topic is here.
Thanks ChrisπŸ™‚πŸ‘

Collapse
 
dailydevtips1 profile image
Chris Bongers

Wohoo glad to contribute to something you needed πŸ™Œ