Back to Documentation

State Management with React Query

Frontend

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:

  1. Type-Safe Queries: Combined with tRPC for end-to-end type safety
  2. Mutation Handling: Manage PDF generation, file compression, etc.
  3. Loading States: Show spinners during async operations
  4. 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

  1. Less Code: Reduces boilerplate significantly
  2. Better UX: Automatic loading and error states
  3. Performance: Intelligent caching reduces network requests
  4. Developer Experience: Excellent TypeScript support

Best Practices

  • Use meaningful query keys
  • Set appropriate stale times
  • Handle errors gracefully
  • Use optimistic updates for better UX