Frontend
React QueryState ManagementCaching
State Management with React Query
Managing server state, caching, and synchronization using TanStack Query.
State Management with React Query
TanStack Query (formerly React Query) simplifies server state management in React applications.
What is React Query?
React Query is a powerful data synchronization library for React that makes fetching, caching, and updating server state simple.
Key Features
Automatic Caching
- Intelligent cache management
- Background refetching
- Stale-while-revalidate pattern
Server State Management
- Handles loading, error, and success states
- Automatic retry logic
- Request deduplication
Synchronization
- Refetch on window focus
- Polling support
- Optimistic updates
Implementation
Basic Query
import { useQuery } from '@tanstack/react-query';
const { data, isLoading, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
});
Mutations
const mutation = useMutation({
mutationFn: createPost,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] });
},
});
In The Workbench
We use React Query with tRPC for:
- Type-Safe Queries: Combined with tRPC for end-to-end type safety
- Mutation Handling: Manage PDF generation, file compression, etc.
- Loading States: Show spinners during async operations
- Error Handling: Display error messages to users
Example from PDF Converter
const pdfMutation = api.pdfConverter.fromHtml.useMutation();
const handleGenerate = async () => {
await pdfMutation.mutateAsync({
html: content,
fileName: 'document',
});
};
Benefits
- Less Code: Reduces boilerplate significantly
- Better UX: Automatic loading and error states
- Performance: Intelligent caching reduces network requests
- Developer Experience: Excellent TypeScript support
Best Practices
- Use meaningful query keys
- Set appropriate stale times
- Handle errors gracefully
- Use optimistic updates for better UX