# React Query Setup - Complete This document summarizes the React Query implementation added to the Black Canyon Tickets React rebuild project. ## What Was Implemented ### 1. QueryClient Provider Setup - **File**: `src/app/providers.tsx` - **QueryClient Configuration**: - `retry: 1` - Retry failed requests once - `staleTime: 30_000` - Data stays fresh for 30 seconds - `gcTime: 600_000` - Data cached in memory for 10 minutes - `refetchOnWindowFocus: false` - Don't refetch when window regains focus - **Development Tools**: React Query DevTools enabled in development mode - **Helper Functions**: `invalidate()`, `getCachedData()`, `setCachedData()` for cache management ### 2. Provider Integration - **File**: `src/App.tsx` - Added `QueryProvider` to the provider stack, wrapping the entire application - Properly positioned in provider hierarchy for optimal context access ### 3. Converted Hooks to React Query #### 3.1 useCheckout Hook - **File**: `src/hooks/useCheckout.ts` - **Converted from**: Raw fetch calls with manual state management - **Converted to**: React Query mutation with automatic error handling - **Usage**: `const checkoutMutation = useCheckout()` #### 3.2 useRefunds Hook - **File**: `src/hooks/useRefunds.ts` (new) - **Purpose**: Handle refund creation with React Query mutations - **Usage**: `const refundMutation = useCreateRefund()` #### 3.3 useTicketVerification Hook - **File**: `src/hooks/useTicketVerification.ts` (new) - **Purpose**: Handle QR ticket verification with React Query mutations - **Usage**: `const verificationMutation = useTicketVerification()` #### 3.4 useOrders Hook - **File**: `src/hooks/useOrders.ts` (new) - **Purpose**: Fetch order details with caching and retry logic - **Usage**: `const orderQuery = useOrder(orderId)` ### 4. Updated Components #### 4.1 TicketPurchase Component - **File**: `src/components/checkout/TicketPurchase.tsx` - **Updated**: Converted to use `useCheckout()` React Query mutation - **Benefits**: Better loading states, error handling, and automatic retries #### 4.2 StripeConnectButton Component - **File**: `src/components/billing/StripeConnectButton.tsx` - **Fixed**: Type errors related to error handling ### 5. Documentation and Examples #### 5.1 ReactQueryExample Component - **File**: `src/components/examples/ReactQueryExample.tsx` - **Purpose**: Complete usage examples for all React Query hooks - **Demonstrates**: Queries, mutations, error handling, cache invalidation #### 5.2 Hooks Index - **File**: `src/hooks/index.ts` - **Purpose**: Centralized exports for all hooks and utilities - **Includes**: Clear separation between React Query hooks and context hooks ## Usage Examples ### Basic Query ```typescript import { useOrder } from '../hooks'; const { data, isLoading, error, refetch } = useOrder(orderId); ``` ### Basic Mutation ```typescript import { useCheckout } from '../hooks'; const checkoutMutation = useCheckout(); const handlePurchase = () => { checkoutMutation.mutate({ orgId: 'org_123', eventId: 'event_456', ticketTypeId: 'tt_789', quantity: 2, customerEmail: 'user@example.com' }); }; ``` ### Cache Management ```typescript import { invalidate } from '../hooks'; // Invalidate specific data invalidate(['order', orderId]); // Invalidate all events invalidate('events'); ``` ## Benefits Achieved ### 1. Performance Improvements - **Automatic Caching**: 30-second stale time reduces unnecessary requests - **Background Refetching**: Data stays current without blocking UI - **Memory Management**: 10-minute garbage collection prevents memory leaks ### 2. Better Developer Experience - **DevTools**: Visual query inspection in development - **TypeScript Support**: Full type safety with mutations and queries - **Consistent API**: All server state uses the same patterns ### 3. Improved Error Handling - **Automatic Retries**: Failed requests retry once by default - **Error States**: Consistent error handling across all components - **Loading States**: Built-in loading states with `isPending`/`isFetching` ### 4. Cache Optimization - **Intelligent Invalidation**: Refresh related data after mutations - **Optimistic Updates**: Support for immediate UI updates - **Background Sync**: Keep data fresh without user intervention ## Migration Notes ### What Changed - Raw fetch calls → React Query mutations - Manual loading states → Automatic `isPending` states - Manual error handling → Automatic error states - No caching → Intelligent caching with invalidation ### What Stayed the Same - Component interfaces remain unchanged - Error handling patterns consistent with existing code - All existing functionality preserved ### Legacy Support - Store-based hooks (Zustand) remain unchanged - Context-based hooks (auth, theme) work alongside React Query - Existing components continue to work without modification ## Next Steps ### Recommended Enhancements 1. **Add more queries**: Convert remaining fetch calls to React Query 2. **Implement optimistic updates**: For better perceived performance 3. **Add background sync**: Keep data fresh when app regains focus 4. **Cache persistence**: Save query cache to localStorage for offline support ### Monitoring - Use React Query DevTools to monitor query performance - Watch for excessive refetching or cache misses - Monitor bundle size impact (current overhead is minimal) ## Configuration The default configuration is optimized for the Black Canyon Tickets use case: - **Short stale time (30s)**: Ticket data changes frequently - **Medium cache time (10min)**: Balance between performance and memory usage - **Single retry**: Avoid hammering APIs while handling transient failures - **No focus refetch**: Prevent unnecessary requests during normal usage All configuration can be adjusted in `src/app/providers.tsx` as needed.