Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

QueryClientProvider.tsx

90 lines2.4 KB

1'use client'
2import * as React from 'react'
3​
4import type { QueryClient } from '@tanstack/query-core'
5​
6/**
7 * The context that `useQueryClient` reads from. `QueryClientProvider` is the
8 * normal way to set it.
9 */
10export const QueryClientContext = React.createContext<QueryClient | undefined>(
11 undefined,
13​
14/**
15 * The `useQueryClient` hook returns the current `QueryClient` instance.
16 *
17 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
18 * one from the nearest context will be used.
19 * @returns The current `QueryClient` instance.
20 * @throws {Error} If no `queryClient` argument is passed and no
21 * `QueryClientProvider` is found in the component tree.
22 */
23export const useQueryClient = (queryClient?: QueryClient) => {
24 const client = React.useContext(QueryClientContext)
25​
26 if (queryClient) {
27 return queryClient
28 }
29​
30 if (!client) {
31 throw new Error('No QueryClient set, use QueryClientProvider to set one')
32 }
33​
34 return client
36​
37/** The props accepted by `QueryClientProvider`. */
38export type QueryClientProviderProps = {
39 /**
40 * **Required**
41 *
42 * The `QueryClient` instance to provide.
43 */
44 client: QueryClient
45 /** The components that get access to the provided `QueryClient`. */
46 children?: React.ReactNode
48​
49/**
50 * Use the `QueryClientProvider` component to connect and provide a
51 * `QueryClient` to your application. Also calls
52 * `client.mount()`/`client.unmount()` as this component mounts/unmounts, which
53 * subscribes the client to focus/online events (resuming any paused mutations
54 * and refetching as needed when the app regains focus or comes back online).
55 *
56 * @example
57 * ;```tsx
58 * import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
59 *
60 * const queryClient = new QueryClient()
61 *
62 * function App() {
63 * return (
64 * <QueryClientProvider client={queryClient}>...</QueryClientProvider>
65 * )
66 * }
67 * ```
68 *
69 * @param props - The `client` to provide, and the `children` that get access to
70 * it.
71 * @returns The provided `children`, wrapped so they can read the `QueryClient`
72 * via `useQueryClient`.
73 */
74export const QueryClientProvider = ({
75 client,
76 children,
77}: QueryClientProviderProps): React.JSX.Element => {
78 React.useEffect(() => {
79 client.mount()
80 return () => {
81 client.unmount()
82 }
83 }, [client])
84​
85 return (
86 <QueryClientContext.Provider value={client}>
87 {children}
88 </QueryClientContext.Provider>
89 )