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

QueryClientProvider.tsx

84 lines2.4 KB

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