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

QueryClientProvider.tsx

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