By Hemanta Sundaray on 2022-11-20
Before we can use useQuery & useMutation (hooks exported by React Query), we must create a query client and provide it to our app.
In a React project, that would look something like this:
import React from "react"
import ReactDOM from "react-dom/client"
import "./index.css"
import App from "./App"
import { BrowserRouter as Router } from "react-router-dom"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
const queryClient = new QueryClient()
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
<React.StrictMode>
<Router>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</Router>
</React.StrictMode>
)
But what does a query client do? Why do we need to provide a query client to our app?
I asked this question to Dominik, the maintainer of React Query (Tanstack Query to be precise).
Here was his answer:
The query client holds the query cache. The query client provider is a React context provider, which allows us to access the client (and thus the cache) without passing it as a prop explicitly.
Everytime we call useQueryClient(), we get the client. The useQuery & useMutation hooks use the query client internally.