query
query copied to clipboard
feat(react-query): add default query options provider
The goal of this PR is to allow providing default query options to a React subtree. So basically like queryClient.setDefaultOptions
/ queryClient.setQueryDefaults
but scoped to a component subtree.
Technically this can already be done in userland, but it would require reading in the context before each useQuery and/or creating a custom useQuery hook. This PR would allow to do it without any changes to useQuery calls.
Example: automatic polling
import { QueryDefaultOptionsProvider } from '@tanstack/react-query'
// All queries in this page will refetch every 5s
// The same queries in another page will fetch at most once on mount
export const Home = () => {
return (
<QueryDefaultOptionsProvider
options={{ queries: { refetchInterval: () => 5000 } }}
>
...
</QueryDefaultOptionsProvider>
)
}
Benefits for React Native
With React Navigation (the most popular navigation library in React Native), screens in the stack history stay mounted. That does not work well with React Query's default refetchOnWindowFocus
/ refetchOnMount
options that assume that if a component is mounted, then it's on screen. This PR would allow setting global navigation-aware options on queries to reconcile the two behaviors. Something along the line:
import { QueryDefaultOptionsProvider } from '@tanstack/react-query'
export const Screen = () => {
const navigation = useNavigation()
return (
<QueryDefaultOptionsProvider
options={{
queries: {
refetchOnWindowFocus: () => navigation.isFocused(),
},
}}
>
...
</QueryDefaultOptionsProvider>
)
}
⚠️ Attention points
-
I have reused the same interface as
queryClient.setDefaultOptions
, though this PR only supports{ queries: ... }
for now, not{ mutations: ... }
(slightly more work because options defaulting is not completely done inuseMutation
yet, unlikeuseBaseQuery
). -
If the component rendering
<QueryDefaultOptionsProvider>
rerenders, all components callinguseQuery
(and alternatives) will rerender because the options object is not referentially stable. The user needs to memoize the options object to be safe. I've added it to the docs, but an alternative would be to expose the context itself and let the user useQueryDefaultOptionsContext.Provider>
to benefit from this official React eslint rule : https://github.com/jsx-eslint/eslint-plugin-react/blob/master/docs/rules/jsx-no-constructed-context-values.md