Back to all posts
Engineering
Jun 20, 2025•14 min read

Architecting Production-Scale React Applications: A Deep Technical Guide to State Synchronization, Server Cache, and Media Pipelines

A comprehensive engineering guide dissecting how production React frontends coordinate global state, cache asynchronous server queries, implement infinite pagination, and optimize media delivery.

#Introduction: Beyond Component Tutorials

Most frontend tutorials explain React in isolation. They demonstrate how to build a button, toggle a modal, or fetch a static list of items inside a useEffect hook. In production systems, however, components represent only the topmost presentation layer. The real engineering challenges lie beneath the surface: managing asynchronous server state, coordinating multi-dimensional filter combinations, preventing network race conditions, handling pagination without layout thrashing, and serving heavy media without crashing mobile browsers.

When building a high-density discovery application like GameHub, which queries tens of thousands of video game records through the RAWG API, naive architectural choices collapse immediately. If you store server data inside local component state, you trigger cascading re-renders. If you fetch raw media assets directly from third-party CDNs, uncompressed 4K images will exhaust device memory within minutes. If you pass filter states down through five layers of JSX, maintenance becomes impossible.

GameHub Catalog Interface with Multi-Dimensional Filters
GameHub Catalog Interface with Multi-Dimensional Filters

This guide takes a comprehensive, code-level look at the engineering decisions behind GameHub. It explains how to structure a modern React application with TypeScript, Zustand, TanStack Query, and Chakra UI so that it remains resilient, fast, and maintainable.

#1. Decoupling Client State from Server Cache

A fundamental mistake in modern React development is treating all application state identically. Frontend state actually consists of two fundamentally distinct categories:

1. Client State: Ephemeral data owned entirely by the browser. Examples include the current search query, selected genre ID, active dropdown selection, or dark mode preference. This state changes synchronously based on direct user input.

2. Server State: Remote data that belongs to the backend. Examples include game details, genre lists, platform catalogs, and trailer videos. This state is asynchronous, potentially out-of-date, requires loading and error indicators, and needs deduplicated caching.

When you mix these two models (for instance, storing fetched API arrays directly in Redux or useState), your code becomes filled with manual synchronization flags, boilerplate reducers, and race conditions.

To solve this, GameHub uses a dual-engine architecture:

  • Zustand manages client-side filter selections in a tiny, reactive store with zero prop-drilling.
  • TanStack Query (React Query v4) acts as an asynchronous cache manager that fetches, caches, invalidates, and paginates remote server data.
  • Let us examine how these two systems communicate without tightly coupling components.

    #2. The Query Object Pattern with Zustand

    Consider the catalog filtering requirements. A user can:

  • Filter games by genre (Action, RPG, Strategy, etc.)
  • Filter games by parent platform (PC, PlayStation, Xbox, etc.)
  • Sort games by relevance, release date, popularity, or rating
  • Search games by text keywords
  • If each filter is stored in an independent useState hook inside the root component, you are forced to pass four state variables and four updater callbacks down through the component hierarchy. Even worse, handling inter-filter dependencies becomes messy. For example, when a user selects a genre, should the previous search query be wiped out?

    The solution is the Query Object Pattern, implemented through Zustand in src/store.ts:

    typescript
    import { create } from 'zustand';
    
    interface GameQuery {
      genreId?: number;
      platformId?: number;
      sortOrder?: string;
      searchText?: string;
    }
    
    interface GameQueryStore {
      gameQuery: GameQuery;
      setSearchText: (searchText: string) => void;
      setGenreId: (genreId: number) => void;
      setPlatformId: (platformId: number) => void;
      setSortOrder: (sortOrder: string) => void;
    }
    
    const useGameQueryStore = create<GameQueryStore>((set) => ({
      gameQuery: {},
      setSearchText: (searchText) =>
        set(() => ({ gameQuery: { searchText } })),
      setGenreId: (genreId) =>
        set((store) => ({
          gameQuery: { ...store.gameQuery, genreId, searchText: undefined },
        })),
      setPlatformId: (platformId) =>
        set((store) => ({
          gameQuery: {
            ...store.gameQuery,
            platformId,
            searchText: undefined,
          },
        })),
      setSortOrder: (sortOrder) =>
        set((store) => ({
          gameQuery: { ...store.gameQuery, sortOrder },
        })),
    }));
    
    export default useGameQueryStore;

    Why This Design Works

    1. Atomic State Shape: All active filters exist in a single immutable GameQuery object. Any component in the tree can read or update this object without passing props through intermediate containers.

    2. Predictable Reset Semantics: Notice lines 20 and 26. When a user explicitly clicks a genre or a platform, searchText is explicitly cleared to undefined. This prevents a common user experience bug where an active text filter produces zero results when combined with an incompatible category.

    3. Selective Subscriptions: Components subscribe only to the specific slices of the store they care about. For example, PlatformSelector only subscribes to s.gameQuery.platformId, which prevents unnecessary re-renders when the search bar changes.

    #3. Abstracting the Network Layer with Generic Classes

    Directly invoking axios.get or fetch inside components or custom hooks couples your presentation logic to HTTP details like base URLs, authentication tokens, and response wrapper structures.

    GameHub encapsulates all remote communication inside a reusable, strongly-typed generic class in src/services/api-client.ts:

    typescript
    import axios, { AxiosRequestConfig } from 'axios';
    
    export interface FetchResponse<T> {
      count: number;
      next: string | null;
      results: T[];
    }
    
    const axiosInstance = axios.create({
      baseURL: 'https://api.rawg.io/api',
      params: {
        key: 'e53bba19d7914970889f528d70c8e06d',
      },
    });
    
    class APIClient<T> {
      endpoint: string;
    
      constructor(endpoint: string) {
        this.endpoint = endpoint;
      }
    
      getAll = (config: AxiosRequestConfig) => {
        return axiosInstance
          .get<FetchResponse<T>>(this.endpoint, config)
          .then((res) => res.data);
      };
    
      get = (id: number | string) => {
        return axiosInstance
          .get<T>(this.endpoint + '/' + id)
          .then((res) => res.data);
      };
    }
    
    export default APIClient;

    Engineering Advantages of this Abstraction

  • Standardized Response Envelope: RAWG wraps list endpoints in { count, next, results }. By defining FetchResponse<T>, any entity (Game, Genre, Platform, Screenshot) immediately inherits full compile-time type safety.
  • Config Encapsulation: Upstream query parameters, including the API authentication key and base URL, are configured in one location. If the authentication method shifts to an HTTP Bearer header tomorrow, only this file changes.
  • Instance Reusability: Hook files instantiate typed service clients cleanly:
  • ```typescript

    const apiClient = new APIClient<Game>('/games');

    const genreClient = new APIClient<Genre>('/genres');

    ```

    #4. Server Cache Strategies and Cold-Start Optimization

    One of the largest performance bottlenecks in data-heavy web apps is network round-trip delay on initial page load. When a user first lands on the homepage, the application needs:

  • The list of available genres for the sidebar
  • The list of platforms for the filter dropdown
  • The first page of games
  • If all three requests execute cold against the network, the user sees empty dropdowns and multiple flickering skeleton loaders.

    However, consider the nature of the data:

  • Video game genres (Action, RPG, Strategy) rarely change.
  • Parent platforms (PC, PlayStation, Xbox, Nintendo) rarely change.
  • GameHub eliminates cold-start latency by pairing TanStack Query with static cache hydration in src/hooks/useGenres.ts:

    typescript
    import { useQuery } from '@tanstack/react-query';
    import ms from 'ms';
    import genres from '../data/genres';
    import APIClient from '../services/api-client';
    import Genre from '../entities/Genre';
    
    const apiClient = new APIClient<Genre>('/genres');
    
    const useGenres = () =>
      useQuery({
        queryKey: ['genres'],
        queryFn: apiClient.getAll,
        staleTime: ms('24h'),
        initialData: genres,
      });
    
    export default useGenres;

    The Power of `initialData` and `staleTime`

    1. Zero Skeleton Flash: By providing initialData: genres (a static snapshot bundled at build time), TanStack Query initializes the cache synchronously. The genre sidebar renders instantly during the very first paint.

    2. 24-Hour Cache Window: Setting staleTime: ms('24h') instructs TanStack Query that this data remains fresh for an entire day. It will not refetch the genres on window focus, route transition, or component remount.

    3. Identical Pattern for Platforms: src/hooks/usePlatforms.ts uses the exact same pattern for platform lists. As a result, both filter controls are interactive immediately without a single network request.

    #5. Infinite Pagination Engine with TanStack Query

    Traditional numeric pagination (Page 1, 2, 3...) creates friction in media discovery catalogs. Users prefer continuous scrolling feeds. However, implementing infinite scrolling manually requires tracking current page offsets, appending arrays without duplicates, handling scroll throttle events, and managing abort controllers.

    GameHub achieves this in src/hooks/useGames.ts by pairing TanStack Query's useInfiniteQuery with Zustand:

    typescript
    import { useInfiniteQuery } from '@tanstack/react-query';
    import ms from 'ms';
    import APIClient, { FetchResponse } from '../services/api-client';
    import useGameQueryStore from '../store';
    import Game from '../entities/Game';
    
    const apiClient = new APIClient<Game>('/games');
    
    const useGames = () => {
      const gameQuery = useGameQueryStore((s) => s.gameQuery);
    
      return useInfiniteQuery<FetchResponse<Game>, Error>({
        queryKey: ['games', gameQuery],
        queryFn: ({ pageParam = 1 }) =>
          apiClient.getAll({
            params: {
              genres: gameQuery.genreId,
              parent_platforms: gameQuery.platformId,
              ordering: gameQuery.sortOrder,
              search: gameQuery.searchText,
              page: pageParam,
            },
          }),
        getNextPageParam: (lastPage, allPages) => {
          return lastPage.next ? allPages.length + 1 : undefined;
        },
        staleTime: ms('24h'),
      });
    };
    
    export default useGames;

    How the Mechanics Work Behind the Scenes

  • Query Key as an Automatic Cache Matrix: The query key is ['games', gameQuery]. Because gameQuery is a JavaScript object containing the active genre, platform, sort order, and search text, TanStack Query automatically treats every unique filter combination as its own isolated cache entry.
  • When the user changes a filter in Zustand, gameQuery updates. TanStack Query detects the key change, instantly renders cached data if available, or cancels any inflight query and triggers a new fetch.
  • Page Param Resolution: getNextPageParam inspects the RAWG API response. If lastPage.next exists, it increments the page number; otherwise, it returns undefined, which signals that no more pages remain.
  • On the UI side, src/components/GameGrid.tsx consumes this hook and integrates with react-infinite-scroll-component:

    typescript
    import { SimpleGrid, Spinner, Text } from "@chakra-ui/react";
    import React from "react";
    import InfiniteScroll from "react-infinite-scroll-component";
    import useGames from "../hooks/useGames";
    import GameCard from "./GameCard";
    import GameCardContainer from "./GameCardContainer";
    import GameCardSkeleton from "./GameCardSkeleton";
    
    const GameGrid = () => {
      const {
        data,
        error,
        isLoading,
        fetchNextPage,
        hasNextPage,
      } = useGames();
      const skeletons = [1, 2, 3, 4, 5, 6];
    
      if (error) return <Text>{error.message}</Text>;
    
      const fetchedGamesCount =
        data?.pages.reduce((total, page) => total + page.results.length, 0) || 0;
    
      return (
        <InfiniteScroll
          dataLength={fetchedGamesCount}
          hasMore={!!hasNextPage}
          next={() => fetchNextPage()}
          loader={<Spinner />}
        >
          <SimpleGrid
            columns={{ sm: 1, md: 2, lg: 3, xl: 4 }}
            spacing={6}
            padding="10px"
          >
            {isLoading &&
              skeletons.map((skeleton) => (
                <GameCardContainer key={skeleton}>
                  <GameCardSkeleton />
                </GameCardContainer>
              ))}
            {data?.pages.map((page, index) => (
              <React.Fragment key={index}>
                {page.results.map((game) => (
                  <GameCardContainer key={game.id}>
                    <GameCard game={game} />
                  </GameCardContainer>
                ))}
              </React.Fragment>
            ))}
          </SimpleGrid>
        </InfiniteScroll>
      );
    };
    
    export default GameGrid;

    Notice how data.pages is iterated. Each page in data.pages corresponds to a chunk of results returned from the paginated endpoint. As the user reaches the bottom of the viewport, fetchNextPage() appends a new page to the cache without wiping previously rendered DOM nodes.

    #6. Dynamic CDN URL Slicing for Image Optimization

    Modern game studios output promotional assets at 4K resolution. Delivering these uncompressed images to a mobile device will consume tens of megabytes per screen, trigger severe scrolling stutters, and cause memory crashes.

    Many junior developers assume that solving this requires deploying a serverless image proxy running Node.js and sharp. That adds backend latency and operational costs.

    Because the RAWG API media backend supports on-the-fly image transformations via URL segments, GameHub solves this with a zero-cost client-side utility in src/services/image-url.ts:

    typescript
    import noImage from '../assets/no-image-placeholder.webp';
    
    const getCroppedImageUrl = (url: string) => {
      if (!url) return noImage;
      
      const target = 'media/';
      const index = url.indexOf(target) + target.length;
      return url.slice(0, index) + 'crop/600/400/' + url.slice(index);
    }
    
    export default getCroppedImageUrl;

    How URL Slicing Operates

    Suppose the RAWG API returns:

    text
    https://media.rawg.io/media/games/b8c/b8c243eaa0fbac8115e0cdccac3f91dc.jpg

    The function detects the media/ string boundary, inserts crop/600/400/, and outputs:

    text
    https://media.rawg.io/media/crop/600/400/games/b8c/b8c243eaa0fbac8115e0cdccac3f91dc.jpg

    This simple transformation instructs the CDN edge to resize and crop the image to exactly 600x400 pixels before transmitting bytes over the network. This slashes average image payload size from 2MB down to under 50KB, reducing total bandwidth consumption by more than 80%. If the upstream record lacks an image entirely, it gracefully falls back to a locally bundled WebP placeholder.

    #7. Deep-Dive View: Dynamic Routing and Attribute Composition

    When navigating to a specific game (/games/:slug), the application switches from catalog browsing to in-depth technical inspection.

    Game Details View with Trailers and System Attributes
    Game Details View with Trailers and System Attributes

    In src/pages/GameDetailPage.tsx, the layout splits into two coordinated columns:

    typescript
    const GameDetailPage = () => {
      const { slug } = useParams();
      const { data: game, isLoading, error } = useGame(slug!);
    
      if (isLoading) return <Spinner />;
      if (error || !game) throw error;
    
      return (
        <SimpleGrid columns={{ base: 1, md: 2 }} spacing={5}>
          <GridItem>
            <Heading>{game.name}</Heading>
            <ExpandableText>{game.description_raw}</ExpandableText>
            <GameAttributes game={game} />
          </GridItem>
          <GridItem>
            <GameTrailer gameId={game.id} />
            <GameScreenshots gameId={game.id} />
          </GridItem>
        </SimpleGrid>
      );
    };

    Key Engineering Insights in the Detail View

    1. Declarative Error Boundaries: Notice line 6. Instead of rendering messy inline error state, the component throws unhandled errors up to React Router 6's root errorElement (src/pages/ErrorPage.tsx), which inspects route errors with isRouteErrorResponse and renders a clean recovery UI.

    2. Component Specialization:

    - ExpandableText: Enforces a 300-character boundary on lengthy synopsis strings, with a smooth expand/collapse toggle to maintain vertical rhythm.

    - GameAttributes: Uses semantic HTML definition lists (<dl>, <dt>, <dd>) styled via Chakra UI for accessibility and clean data presentation.

    - GameTrailer: Fetches video streams and renders HTML5 video controls defaulting to 480p streams to preserve mobile bandwidth.

    - GameScreenshots: Queries the /games/:id/screenshots endpoint and generates a two-column responsive gallery.

    #8. Lessons for Engineering Students and Frontend Architects

    Building production-grade user interfaces is not about writing clever one-liners; it is about establishing clear system boundaries and anticipating failure modes.

    Here are the four foundational takeaways from the GameHub codebase:

    1. Separate Client State from Server State: Never store remote API responses in global state containers like Redux or Zustand unless you need to mutate them optimistically offline. Let TanStack Query manage cache invalidation, loading indicators, and retry cycles. Use Zustand solely for user interactions, filter parameters, and client preferences.

    2. Encapsulate Filtering with the Query Object Pattern: When your application allows users to slice and dice data across multiple dimensions, avoid fragmented state. Group parameters into a single typed object so queries stay synchronized and cache keys remain predictable.

    3. Seed Static Reference Data: Not every piece of data needs to trigger a network request. Identify reference datasets that change infrequently (categories, tags, platforms, supported currencies) and seed them using initialData with extended staleTime.

    4. Optimize Media at the CDN Edge: Bandwidth is the silent killer of frontend performance. Before writing heavy image processing workers or downloading massive raw files, leverage CDN manipulation parameters to deliver only the pixels the client actually needs.

    By applying these architectural patterns, you transform a fragile prototype into a resilient, production-ready web application capable of scaling to hundreds of thousands of records smoothly.

    HOME✦ABOUT✦PROJECTS✦BLOG✦
    >_ READY TO COLLABORATE?

    GOT SOME EXCITING IDEAS? LET'S CONNECT AND BUILD SOMETHING EXTRAORDINARY TOGETHER!

    lohitkumar1914@gmail.com✦lohitkumar1914@gmail.com✦lohitkumar1914@gmail.com✦lohitkumar1914@gmail.com✦
    CLICK TO COPY EMAIL
    Designed by Lohit Kumar