I have several components that make use of user details.
Since user details don't change that often, I want to fetch them only once.
One way would be -
const twentyFourHoursInMs = 1000 * 60 * 60 * 24
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
refetchOnmount: false,
refetchOnReconnect: false,
retry: false,
staleTime: twentyFourHoursInMs,
},
},
})
Other way is to fetch data once in base component and use cached data in other components by using queryClient.getQueryData('user')
Which way would be better?
queryClient.getQueryData('user') is not a good way to access data in component, because it doesn't create a subscription like useQuery does. Even if you set a high staleTime, you might want to manually invalidate the query.
One example would be on a user details page, where the user changes their name. After making the mutation, you'd likely want to invalidate the user details query, or update the data from the mutation response with queryClient.setQueryData.
In those cases, you would want your components that depend on the user details query to re-render with the new data, and for that, you need useQuery.
if you want a true "only once" fetching, you'd need:
staleTime: Infinity
cacheTime: Infinity
staleTime, you define how long a resource is considered as fresh. As long as it is fresh, data will come from the cache only.cacheTime, you avoid that the query is garbage collected. Per default, if you unmount all the components that have an observer (via useQuery), the query is considered as inactive and will then be garbage collected after 15 minutes. That's another reason to prefer useQuery - because it creates an observer that keeps your query active.refetchOn... flags. React Query will only do those smart refetches on certain events if the data is stale - which is never if you set infinity staleTime.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With