Skip to content

About

This is a production-quality Proof of Concept (POC) demonstrating React Query (TanStack Query) best practices and core concepts through a Library Management System.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

React Query POC - Comprehensive Implementation

This is a production-quality Proof of Concept (POC) demonstrating React Query (TanStack Query) best practices and core concepts through a Library Management System.

πŸ“š Concepts Demonstrated

Query Fundamentals

  • βœ… Basic query setup with useQuery
  • βœ… Query keys and dependency management
  • βœ… Query lifecycle (fresh, fetching, stale, inactive)
  • βœ… Automatic background refetching
  • βœ… Cache deduplication
  • βœ… Query invalidation

Data Fetching Patterns

  • βœ… On-Demand Fetching: Manual query triggering
  • βœ… Polling: Automatic refetch intervals
  • βœ… Dependent Queries: Queries that depend on previous query results
  • βœ… Parallel Queries: Multiple queries running simultaneously
  • βœ… Pagination: Cursor and page-based pagination
  • βœ… Infinite Queries: Infinite scroll implementation

Cache Management

  • βœ… Deduplication: Prevents duplicate requests
  • βœ… Garbage Collection: Automatic cleanup of unused cache
  • βœ… Cache Time: Control cache retention
  • βœ… Stale Time: Control when data is considered stale
  • βœ… Window Focus Refetching: Re-fetch on window focus
  • βœ… Optimistic Updates: Update UI before server confirmation

Mutations

  • βœ… Basic mutations with useMutation
  • βœ… Mutation success/error handling
  • βœ… Optimistic updates
  • βœ… Cache invalidation after mutations
  • βœ… Rollback on error

Advanced Features

  • βœ… Error boundaries and error handling
  • βœ… Loading states and suspense
  • βœ… Prefetching
  • βœ… Query retries with exponential backoff
  • βœ… Request cancellation
  • βœ… TypeScript integration

πŸ—οΈ Architecture

src/
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ client.ts          # API client configuration
β”‚   β”œβ”€β”€ books.api.ts       # Books API endpoints
β”‚   β”œβ”€β”€ reviews.api.ts     # Reviews API endpoints
β”‚   └── users.api.ts       # Users API endpoints
β”œβ”€β”€ hooks/
β”‚   β”œβ”€β”€ queries/
β”‚   β”‚   β”œβ”€β”€ useBooks.ts    # Book-related queries
β”‚   β”‚   β”œβ”€β”€ useReviews.ts  # Review queries
β”‚   β”‚   └── useUsers.ts    # User queries
β”‚   └── mutations/
β”‚       β”œβ”€β”€ useBookMutations.ts    # Book mutations
β”‚       └── useReviewMutations.ts  # Review mutations
β”œβ”€β”€ types/
β”‚   β”œβ”€β”€ book.types.ts      # Book-related types
β”‚   β”œβ”€β”€ review.types.ts    # Review types
β”‚   └── api.types.ts       # API response types
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ books/             # Book-related components
β”‚   β”œβ”€β”€ reviews/           # Review components
β”‚   β”œβ”€β”€ common/            # Shared components
β”‚   └── layout/            # Layout components
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ Books.tsx          # Books listing page
β”‚   β”œβ”€β”€ BookDetail.tsx     # Book detail page
β”‚   β”œβ”€β”€ Reviews.tsx        # Reviews page
β”‚   └── Dashboard.tsx      # Dashboard with stats
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ queryClient.ts     # Query client configuration
β”‚   └── helpers.ts         # Utility functions
β”œβ”€β”€ App.tsx                # Main app component
└── main.tsx              # Entry point

πŸš€ Getting Started

Prerequisites

  • Node.js 18+
  • npm or yarn

Installation

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

# Preview production build
npm run preview

πŸ“– Key Features

1. Book Management

  • View all books with pagination
  • Search and filter books
  • View book details with reviews
  • Check book availability
  • Checkout/return books

2. Review System

  • View reviews for books
  • Add new reviews
  • Edit/delete reviews (optimistic updates)
  • Real-time review updates

3. Activity Feed

  • Latest activity across the library
  • Polling for new activities
  • Activity filters

4. Search

  • Instant search with debouncing
  • Search across books, authors, and genres

🎯 React Query Patterns Demonstrated

Query Keys Pattern

// Hierarchical query keys for easy invalidation
['books'] // All books
['books', { page: 1 }] // Books page 1
['books', bookId] // Specific book
['books', bookId, 'reviews'] // Book reviews

Dependent Queries

// Only fetch reviews after book data is loaded
const { data: book } = useBook(bookId);
const { data: reviews } = useBookReviews(bookId, {
  enabled: !!book,
});

Optimistic Updates

// Update UI immediately, rollback on error
mutate(newData, {
  onMutate: async (newData) => {
    // Cancel outgoing refetches
    await queryClient.cancelQueries({ queryKey: ['books'] });
    
    // Snapshot previous value
    const previous = queryClient.getQueryData(['books']);
    
    // Optimistically update
    queryClient.setQueryData(['books'], (old) => [...old, newData]);
    
    return { previous };
  },
  onError: (err, newData, context) => {
    // Rollback on error
    queryClient.setQueryData(['books'], context.previous);
  },
});

Infinite Scroll

const {
  data,
  fetchNextPage,
  hasNextPage,
  isFetchingNextPage,
} = useInfiniteQuery({
  queryKey: ['books', 'infinite'],
  queryFn: ({ pageParam = 0 }) => fetchBooks(pageParam),
  getNextPageParam: (lastPage) => lastPage.nextCursor,
});

πŸ”§ Configuration

Query Client Setup

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 1000 * 60 * 5, // 5 minutes
      gcTime: 1000 * 60 * 30, // 30 minutes (formerly cacheTime)
      refetchOnWindowFocus: true,
      refetchOnReconnect: true,
      retry: 3,
      retryDelay: (attemptIndex) => 
        Math.min(1000 * 2 ** attemptIndex, 30000),
    },
  },
});

πŸ“ Mock API

The POC includes a complete mock API that simulates:

  • Network delays
  • Error scenarios
  • Pagination
  • Search functionality
  • CRUD operations

🎨 UI Notes

The UI is intentionally simple and functional to keep focus on React Query implementation patterns. The emphasis is on:

  • Clean, maintainable code
  • Proper error handling
  • Loading state management
  • TypeScript type safety
  • Production-ready patterns

πŸ“š Learning Resources

Each component includes detailed comments explaining:

  • Why specific React Query options are used
  • How the query/mutation works
  • Best practices being followed
  • Common pitfalls to avoid

🀝 Contributing

This POC is designed as a reference implementation. Feel free to:

  • Extend with additional features
  • Add more complex query patterns
  • Improve UI/UX
  • Add tests

πŸ“„ License

MIT

πŸ™ Acknowledgments

Based on "The Official React Query Course" by ui.dev

About

This is a production-quality Proof of Concept (POC) demonstrating React Query (TanStack Query) best practices and core concepts through a Library Management System.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages