React Query - query is not using cache?

Viewed 4260

I have the following definition of useQuery that i use in a couple of React components:

useQuery("myStuff", getMyStuffQuery().queryFn);

Where getMyStuffQuery looks like this:

export const getMyStuffQuery = () => {
    return {
    queryFn: () => makeSomeApiCall(),
}}

I would expect that although all of those components render, makeSomeApiCall() would only make an API call once, and the rest of the time will use the cache resulted in from this first call.

However, it seems like it keeps calling makeSomeApiCall() again and again, whenever any of said components renders.

Why is React Query not using the cache? Am i doing something wrong?

1 Answers

React Query will cache the data of the query by default, but that does not affect whether or not it thinks that data is stale. If it thinks data is stale, it will call the query function (hit the API) every time useQuery() is called. This means it will read the data from the cache if it has it, but since it thinks that data is stale, will still hit the API in the background to fetch any updated data.

Fortunately, you have complete control over whether or not React Query considers data to be stale. You can set a staleTime config option to control how long specific data should be considered fresh. You can even set it to Infinity to say that as long as your app is open, it should only ever call the query function (hit the API) one time. By default this value is 0, which is why you are seeing the behavior you are - React Query will refetch the data in the background every time useQuery is called because it immediately thinks that data is stale (even though it's still cached).

In your example, if you truly ever only wanted an API to be called one time, you could simply set the staleTime option to Infinity.

useQuery("myStuff", getMyStuffQuery().queryFn, { staleTime: Infinity });

This option, along with all others, can be read about in the docs here https://react-query.tanstack.com/reference/useQuery

Related