Tanstack React Query
Use React Query selectively for client-side components in Next.js
Optional Feature
StarterKitPro keeps the default setup lean. React Query is not included out-of-the-box but can be easily added in under a minute if you want to use it.
Using React Query Selectively in Next.js
Core Guidance:
- Fetch Data: Use Server Components (Next.js standard).
- Mutate Data: Use Server Actions (Next.js standard).
- React Query Use Case: Primarily for client-side caching when a component needs to refetch the same data repeatedly (e.g., after filtering/sorting), preventing excess API calls.
Complexity Alert
Avoid React Query for initial loads (prefer Server Components) or mutations (prefer Server Actions) to prevent complexity and potential hydration issues.
Usually Not Needed
Native Next.js features (Server Components, Actions, API Routes) cover most needs. Use React Query only when client-side caching offers a clear benefit.
Pattern (When using React Query for Caching):
- Use React Query in client components for caching subsequent API calls.
- Use Server Actions for mutations.
- After a Server Action, invalidate the React Query cache (
useClearCache
).
Setup
Let's set up React Query step by step:
1. Installation
2. Query Client Provider
Create a provider to configure the QueryClient
.
3. Wrap Your Application
Wrap your root layout with the CustomQueryClientProvider
.
Fetching Data with API Routes
1. Custom Hooks for Queries
Encapsulate fetching logic and cache invalidation in custom hooks.
Use parameterized query keys (e.g., ["tasksAPI", userId]
) for dynamic
queries.
2. Using Hooks in Components
Call your custom fetching hook within client components.
Invalidating Cache After Action
Use the useClearCache
hook to invalidate relevant query keys after an action (e.g., Server Action mutation) modifies data.
Invalidating keys like ["tasksAPI"]
ensures components using
useFetchTasksAPI
refetch data.
Using Server Actions for Fetching
Alternatively, call Server Actions directly within queryFn
if needed, using distinct query keys.
Best Practices Summary
- Fetch: Use API Routes + React Query (
useQuery
). - Mutate: Use Server Actions.
- Invalidate: After Server Action mutation, use
useClearCache
to invalidate relevant API Route query keys. - Custom Hooks: Encapsulate query logic.
- Query Keys: Use specific, array-based keys.
- Error Handling: Handle errors in components or
onError
.
Conclusion
Pairing React Query with API Routes for fetching and Server Actions for mutations provides a robust pattern for managing client-side data in Next.js. Use useClearCache
to bridge the gap, ensuring data freshness after mutations.