Setting up TanStack Query in a React Project
Showcase the installation and basic setup of TanStack Query in a React application, including wrapping the root component with QueryClientProvider.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
First, import QueryClient and QueryClientProvider from '@tanstack/react-query', along with React and ReactDOM for rendering, and the App component.
const queryClient = new QueryClient();
Initialize a new QueryClient instance. This will be used to configure our queries and mutations.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
);
Wrap the App component with QueryClientProvider and pass the queryClient instance. This allows any child component of App to use the features provided by TanStack Query.