TanStack Query (React Query) in React + Vite + TypeScript
This guide provides a production-ready architectural pattern for implementing TanStack Query in a React application. It focuses on scalability, type safety, and maintainability.
$ npx @airuleshub/cli@latest add tanstack-query-react-query-in-react-vite-typescriptRule Content
The Guide to TanStack Query (React Query) in React + Vite + TypeScript
This guide provides a production-ready architectural pattern for implementing TanStack Query in a React application. It focuses on scalability, type safety, and maintainability.
1. Installation & Setup
First, install the core package and the devtools.
Global Configuration (src/main.tsx)
Wrap your application in QueryClientProvider.
2. Recommended Directory Structure
Isolate your data fetching logic from your UI components.
3. Query Key Factory Pattern (src/lib/query-keys.ts)
Crucial: Never hardcode query keys (strings/arrays) directly in your components. Use a factory to maintain consistency.
4. The API Layer (src/api/*)
Keep API calls strictly as pure functions returning Promises. They should know nothing about React.
5. Custom Hooks (The "Glue" Layer)
Wrap useQuery and useMutation in custom hooks. This gives you a single place to handle key management, types, and default options.
Fetching Data (useQuery)
Mutating Data (useMutation)
Always invalidate related queries on success to keep the UI in sync.
6. Usage in Components
Components become clean and focused purely on UI logic.
7. Advanced Patterns
Optimistic Updates
Update the UI immediately before the server responds.
Type-Safe Error Handling
Define a global error type for your API.
8. Best Practices Checklist
- Global Stale Time: Set a reasonable global
staleTime(e.g., 5 mins) to avoid excessive background fetching. - Query Key Factories: Always use a factory/object for keys (
todoKeys.list(filter)). - Separation of Concerns:
Component->Custom Hook->API Function. - Invalidation: Always invalidate parent lists when creating/deleting items.
- DevTools: Keep
ReactQueryDevtoolsin your app wrapper (it's stripped in production).
