Subscribe

Automatically refetching with React Query

✍️

Adding a option to React Query to automatically refetch data

7 Feb, 2022 · 2 min read

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 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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Conditional wrapping in React

11 Dec, 2022 · 4 min read

Conditional wrapping in React

Have you tried React classnames?

26 Oct, 2022 · 2 min read

Have you tried React classnames?

Join 2097 devs and subscribe to my newsletter