- Published on
Apollo client has some built in features that can help reduce network requests.
You set it up like this:
const { loading, error, data } = useQuery(GET_DOGS, {
fetchPolicy: "network-only" // Doesn't check cache before making a network request
});
There is also nextFetchPolicy
. When this is used with fetchPolicy
, the fetchPolicy
is used for the first request, and nextFetchPolicy
for all future requests.
const { loading, error, data } = useQuery(GET_DOGS, {
fetchPolicy: "network-only", // Used for first execution
nextFetchPolicy: "cache-first" // Used for subsequent executions
});
The different fetch policies
cache-first
- If the requested data is in the cache: use the cached version.
- If not then request the data, and store the response in the cache
- This is the default cache policy
cache-only
- If the request data is in the cache: use the cached version
- Otherwise it will throw an error
- This policy will never make a network request.
cache-and-network
- If the requested data is in the cache use that cached data (for now)
- At the same time always make a network request for the latest data, then when that comes back if it is different to the cached version update the cache.
- Good for UI as it feels quick, but also keeps everything up to date.
network-only
- Make a network request for the data (it does not check if it was already in the cache)
- When the data comes back set the cache with that data.
- This is good if you need the most recent version of the data, as it will not show out of date data. It will feel a bit more laggy in the UI though as you wait for the data to be returned.
no-cache
- The same as
network-only
, but it won't set the cache once the data comes back.
standby
- Uses the same logic as cache-first, except this query does not automatically update when underlying field values change. You can still manually update this query with refetch and updateQueries.
refetch
If you use the refetch
function (from useQuery()
) the fetch policy is set to network-only
to guarantee a network request.
(unless the original query had its fetchPolicy as no-cache
or cache-and-network
- which also guarantees a network request)