feat(react-query): add default query options provider #7409
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
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: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