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

QueryClientProvider.tsx

86 lines2.3 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 *
16 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
17 * be used.
18 * @returns The current `QueryClient` instance.
19 * @throws If no `queryClient` argument is passed and no `QueryClientProvider` is found in the 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 *
57 * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
58 *
59 * @example
60 * ```tsx
61 * import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
62 *
63 * const queryClient = new QueryClient()
64 *
65 * function App() {
66 * return <QueryClientProvider client={queryClient}>...</QueryClientProvider>
67 * }
68 * ```
69 */
70export const QueryClientProvider = ({
71 client,
72 children,
73}: QueryClientProviderProps): React.JSX.Element => {
74 React.useEffect(() => {
75 client.mount()
76 return () => {
77 client.unmount()
78 }
79 }, [client])
80​
81 return (
82 <QueryClientContext.Provider value={client}>
83 {children}
84 </QueryClientContext.Provider>
85 )