Share E-Book

AuthorAlan Alickovic, Anthony Alicea

Master modern React application architecture patterns and principles for building scalable, maintainable production apps and learn best practices in project structure, component design, state management, testing strategies, and more. Key Features Master React architecture patterns and design principles for building maintainable, scalable frontend applications Develop production-ready React applications using proven methodologies from planning to production deployment Learn to make informed technology decisions and design scalable frontend systems that evolve with your needs Book Description Building production-grade React applications requires making dozens of architectural decisions, often with little cohesive guidance. This book teaches proven architectural patterns for building scalable, maintainable frontend apps, based on timeless principles and modern best practices. This updated edition features a modern stack: React Router in framework mode, TypeScript, TanStack Query, Zustand, React Hook Form, Zod, Shadcn UI, Vitest, and Playwright. It also adds new chapters on performance, accessibility, and internationalization. You’ll work through a real-world example that brings modern architecture concepts to life. Starting with architectural foundations, you’ll make informed decisions about project structure, enforce code quality, build a well-designed component library, and implement the right rendering strategies. From there, you’ll build robust API layers with types generated from an OpenAPI specification and implement the right state management strategies for each use case. You will also learn about different testing strategies and when to use them, how to secure the application, and how to make it performant so that it remains scalable and maintainable. By the end, you’ll be prepared to design and build scalable React apps from the ground up and lead technical decisions in real-world projects.

AI Reading Assistant

Summary and highlights from this book's index; jump to passages in the text

Passage locations
Tags
No tags
ISBN: 1836202962
Publisher: Packt Publishing
Publish Year: 2026
Language: 英文
Pages: 380
File Format: PDF
File Size: 3.8 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
React Application Architecture for Production Second Edition A hands-on guide to architecting, building, and delivering enterprise-ready modern React apps Alan Alickovic Anthony Alicea
React Application Architecture for Production Second Edition Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Portfolio Director: Ashwin Nair Relationship Lead: Bhavya Rao Project Manager: Vishnu Priya R Content Engineer: Roshan Ravi Kumar Technical Editor: Arjun Varma Copy Editor: Roshan Ravi Kumar Indexer: Hemangini Bari Production Designer: Shankar Kalbhor Growth Lead: Anamika Singh First published: January 2023 Second edition: May 2026 Production reference: 1110526 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-83620-297-4 www.packtpub.com
Contributors About the authors Alan Alickovic is a software engineer, consultant, and creator of Bulletproof React, one of the most popular architecture guides for building React applications. He has spent more than a decade building scalable web applications across startups and large enterprises, giving him practical insights into what works in real-world scenarios. He believes great software is not just functional, but also simple, scalable, and maintainable. Anthony Alicea is a software educator and developer with over 25 years of experience building and teaching web development fundamentals. More than 370,000 students have taken his courses on JavaScript, React, and more. Tony is known for helping developers truly understand how things work beneath the surface. He teaches React online at understandingreact.com.
About the reviewers Gurjit Singh is a Berlin-based Senior Frontend Engineer at Storyblok with over eight years of experience building modern web applications using React, TypeScript, and Node.js. He has a keen interest in developer tooling, along with a focus on performance optimization and building scalable libraries. Previously, at Zendesk, he worked on AI-powered and customer-facing products at scale. He also led a major open-source project for over five years, growing it to more than 30,000 monthly active users and collaborating with engineers from companies such as Apple and Wix. Outside of work, Gurjit enjoys speaking at conferences, sharing practical engineering insights, exploring Indian classical music, reading psychology books, and traveling. Eleke Great is a senior software engineer at Skillseed with seven years of hands-on experience working with JavaScript libraries and frameworks at the production level. He has built and scaled real-world systems and is also the author of Saturday with Codes, a LinkedIn newsletter with over 13,000 subscribers.
Table of Contents Preface xv Free benefits with your book .............................................................................. xxi Chapter 1: Understanding the Architecture of React Applications 1 Why architecture matters ..................................................................................... 2 Architecture as foundation • 3 Coordination and velocity • 3 Speed through clarity • 4 Economics of good architecture • 4 Architecture and product quality • 5 The React architecture challenge .......................................................................... 5 How do we structure the project? • 7 How do we render our application? • 7 How do we manage state? • 8 How do we style components? • 8 How do we handle data fetching? • 8 How do we handle authentication? • 9 How do we test a React application? • 9 The meta-decision • 9 Thinking about architectural decisions ................................................................. 9 Patterns that usually don't work • 10 Patterns that usually work • 11 Planning our application ..................................................................................... 12 Functional requirements: What it does • 13 Non-functional requirements: How it works • 14 The data model • 15 Architectural decisions • 16
Project structure: feature-based • 16 Rendering strategy: hybrid • 17 State management: Multi-tier • 17 Styling: Tailwind CSS + BaseUI • 17 Authentication: Cookie-based • 18 Testing: pragmatic • 18 Summary ........................................................................................................... 18 Chapter 2: Setup and Project Structure Overview 21 Technical requirements ...................................................................................... 22 Choosing a meta framework for the project ......................................................... 23 What is a meta framework, and why do we need it? • 23 The pain points they solve • 23 The React meta framework landscape • 24 Next.js • 24 React Router (in framework mode) • 24 TanStack Start • 24 Making the right choice • 24 Why we're using React Router • 24 How to get started with React Router • 25 Build tool setup overview ................................................................................... 26 What is Vite, and why do we need it? • 26 How Vite works with React Router • 27 Our Vite configuration • 27 Type-checking setup overview ........................................................................... 28 What is TypeScript, and why do we need it? • 28 How TypeScript works • 29 Our TypeScript configuration • 29 React Router type generation • 30 Running TypeScript checks • 31 Linting setup overview ........................................................................................ 31 What is linting, and why do we need it? • 32 Table of Contents vi
ESLint overview • 32 Our ESLint configuration • 32 Running ESLint • 35 Formatting setup overview ................................................................................. 35 What is code formatting, and why do we need it? • 35 How Prettier works • 36 Configuring Prettier • 36 Pre-commit checks setup overview ..................................................................... 37 What are pre-commit hooks, and why do we need them? • 37 How pre-commit hooks work • 37 Our pre-commit workflow • 38 Running pre-commit checks • 39 Project structure overview .................................................................................. 40 What is project structure, and why does it matter? • 40 Different approaches to project structure • 40 File type structure • 41 Feature-based structure • 41 Why we chose the feature-based structure • 42 How the code flows • 43 Application (top-level) • 44 Features (mid level) • 44 Shared utilities (bottom-level) • 45 Why this matters • 45 Enforcing project structure with ESLint • 46 Constraint 1: Shared utilities must remain independent • 47 Constraint 2: Features cannot import from the app • 47 Constraint 3: Feature dependencies are explicit and controlled • 48 Why this matters • 48 ESLint in action • 48 Environment variables setup overview ............................................................... 49 What are environment variables, and why do we need them? • 49 Our environment variable system • 50 vii Table of Contents
Setting up environment variables • 51 Summary ........................................................................................................... 52 Chapter 3: Building and Documenting Components 53 Technical requirements ...................................................................................... 53 Anatomy of a component .................................................................................... 54 What is a component? • 55 Using the component • 56 Creating our component library .......................................................................... 57 What is a component library, and why do we need one? • 57 Different approaches to component libraries • 58 Option 1: Install a package (Material-UI, Ant Design, Chakra UI, Mantine) • 58 Option 2: Build from scratch • 58 Option 3: Shadcn UI (copy-paste components) • 59 Why we chose Shadcn UI • 59 Configuring Shadcn UI • 60 Using the CLI • 60 Adding components • 61 Creating components manually • 64 Documenting components ................................................................................. 65 Creating a component route • 65 What is storybook? • 67 Configuring Storybook • 67 Configuring Vite for storybook • 68 Configuring Storybook preview • 68 Running Storybook • 69 Documenting components with Storybook • 69 Creating a story file • 70 Viewing stories in Storybook • 72 Summary ........................................................................................................... 73 Table of Contents viii
Chapter 4: Routing and Rendering Strategies 75 Technical requirements ...................................................................................... 75 Routing with React Router .................................................................................. 76 Configuring routes in React Router • 76 Navigating between pages • 78 Using Link for basic navigation • 78 Using NavLink for navigation with active states • 79 Using useNavigate for programmatic navigation • 80 Rendering strategies ........................................................................................... 80 Server-side rendering • 81 Creating a server-rendered idea detail page • 82 Client-side rendering • 85 Creating a client-rendered dashboard page • 87 Hybrid rendering • 89 Creating a hybrid profile page • 91 Static pre-rendering • 95 Creating pre-rendered home and about pages • 97 Adding meta tags to pages .................................................................................. 98 Adding page layouts ......................................................................................... 100 Summary ......................................................................................................... 108 Chapter 5: Communicating with the API 111 Technical requirements ...................................................................................... 111 Creating API client ............................................................................................ 113 Generating TypeScript types and validation schemas from OpenAPI specifications ... 117 What is OpenAPI and why generate types? • 118 Configuring type generation • 118 Setting up React Query ...................................................................................... 123 Why React Query? • 124 Configuring React Query for the application • 124 ix Table of Contents
Creating API layer for the application ................................................................. 125 Organizing query keys • 125 Defining queries • 126 Defining mutations • 128 Integrating with the application ........................................................................ 129 Queries • 130 Client-side usage • 130 Server-side usage • 131 Server-side usage via HydrationBoundary • 132 Mutations • 135 Summary .......................................................................................................... 136 Chapter 6: Managing Application State 139 Technical requirements .................................................................................... 140 Managing local state .......................................................................................... 141 Sharing state globally ........................................................................................ 144 Handling asynchronous state ............................................................................. 150 Managing form state ......................................................................................... 155 Persisting state in the URL ................................................................................ 160 Summary ......................................................................................................... 168 Chapter 7: Implementing Authentication and Securing the Application 171 Technical requirements ..................................................................................... 172 Authentication .................................................................................................. 173 Extending the API client • 175 Registration page • 177 Login page • 181 Logging out the user • 184 Accessing the user in the app • 186 Protecting routes • 190 Authorization .................................................................................................... 191 Table of Contents x
Securing the application .................................................................................... 196 Content sanitization • 196 Security headers • 199 Summary ......................................................................................................... 205 Chapter 8: Improving Application Performance 207 Technical requirements .................................................................................... 208 Detecting performance issues ........................................................................... 209 Optimizing components ................................................................................... 210 Colocating state • 211 Memoizing expensive calculations • 214 Using component composition • 216 Code splitting and lazy loading • 219 Streaming content from the server .................................................................... 220 Debouncing user input ..................................................................................... 223 Large data set optimization ............................................................................... 227 Pagination • 227 List virtualization ............................................................................................. 232 Optimistic updates ............................................................................................ 237 Summary ......................................................................................................... 242 Chapter 9: Going International 245 Technical requirements .................................................................................... 246 Understanding internationalization architecture .............................................. 247 Where to store translations • 248 How our i18n system works • 248 Language detection and storage • 249 Server-side rendering with translations • 250 Client-side hydration • 250 Loading translations dynamically • 250 Switching languages • 251 Setting up i18n in our application ...................................................................... 251 xi Table of Contents
Organizing translations with namespaces • 251 App-level translations • 251 Feature-scoped translations • 252 Combining translations • 253 Configuring React-i18next • 254 Creating the i18next middleware • 255 Initializing on the server • 256 Initializing on the client • 258 Serving translations via API • 260 Adding type safety to translation keys • 261 Using translations in the application ................................................................. 262 Using the default namespace • 263 Interpolation • 264 Pluralization • 264 Formatting dates • 265 Switching between languages in the application ............................................... 266 The language switcher component • 267 The API endpoint • 269 Summary ......................................................................................................... 270 Chapter 10: Making the Application Accessible 273 Technical requirements ..................................................................................... 274 Understanding accessibility fundamentals ......................................................... 275 Accessibility principles • 276 Laying the architectural foundation .................................................................. 276 Semantic HTML • 276 Defining page landmarks • 278 Using accessible component libraries • 279 Practical accessibility optimizations ................................................................. 280 Skip links for keyboard navigation • 280 Providing accessible labels • 282 Announcing dynamic changes • 282 Table of Contents xii
Summary ......................................................................................................... 284 Chapter 11: Testing the Application 287 Technical requirements .................................................................................... 287 Why testing is important .................................................................................. 289 Unit testing ...................................................................................................... 290 Integration testing ........................................................................................... 293 End-to-end testing ........................................................................................... 297 Summary .......................................................................................................... 301 Chapter 12: Going to Production 303 Technical requirements .................................................................................... 304 What is CI/CD? ................................................................................................. 305 Using GitHub Actions ....................................................................................... 306 Workflows • 306 Events • 307 Jobs • 307 Steps • 307 Actions • 307 Runners • 307 Configuring the pipeline for continuous integration .......................................... 307 Configuring the pipeline for continuous deployment .......................................... 312 Creating the deployment workflow • 312 Setting up Render • 314 Getting the service ID and API key • 317 Adding secrets to the repository • 319 Verifying the deployment • 319 Summary .......................................................................................................... 321 Chapter 13: Evolving the Application 323 Using AI to enforce application architecture ....................................................... 323 Understanding the right mental model • 324 xiii Table of Contents
Context files • 324 Writing rules that work • 324 Practical use cases • 326 Keeping rules up to date • 326 React server components .................................................................................. 326 Why server components? • 327 Application monitoring and observability .......................................................... 327 Error tracking with Sentry • 327 Performance monitoring • 329 Structured logging and alerts • 329 Feature flags ..................................................................................................... 329 Simple implementation vs dedicated tools • 330 A/B testing • 331 Scaling the API layer .......................................................................................... 331 The BFF pattern • 332 Monorepos ........................................................................................................ 333 Sharing packages across apps • 334 Microfrontends ................................................................................................. 335 When microfrontends make sense • 335 Trade-offs to understand before adopting • 336 Summary ......................................................................................................... 336 Chapter 14: Unlock Your Exclusive Benefits 339 Unlock this Book's Free Benefits in 3 Easy Steps ................................................. 340 Other Books You May Enjoy 345 Index 349 Table of Contents xiv
Preface Building large-scale applications in production with React can be overwhelming due to the number of choices and lack of cohesive resources. This hands-on guide is designed to share practices and examples to help address these challenges in building enterprise-ready applications with React. In this book, we will first discuss the architectural principles behind scalable React applications. Then, we will lay out the foundation of the project with Vite, TypeScript, ESLint, Prettier, and Husky, and organize it with a feature-based folder structure. We will then build reusable, documented components with Shadcn UI and Storybook, and learn how to handle routing and rendering strategies, including pre-rendering, SSR, CSR, and hybrid approaches using React Router in framework mode. Once the foundations are in place, we will cover how to communicate with APIs in a type-safe way using OpenAPI-generated types, Zod validation, and React Query for server state. We will explore the right state management tools for each use case, covering local state, global state, form state, and URL state before implementing cookie-based authentication, authorization policies, and content security practices. Finally, we will improve the quality of the application by optimizing performance with memoization, code splitting, and streaming, adding internationalization with react-i18next, ensuring accessibility by following WCAG principles, and writing a comprehensive test suite with Vitest and Playwright. We will finish by setting up a CI/CD pipeline with GitHub Actions and looking at advanced topics such as enforcing the architecture with AI, React Server Components, feature flags, monorepos, and microfrontends. By the end of the book, you will be able to efficiently build production-ready applications by following industry practices and expert tips. Who this book is for This book is for intermediate-level web developers who already have a good understanding of JavaScript, React, and web development in general and want to build large-scale React applications effectively. Besides experience with JavaScript and React, some experience with TypeScript will be beneficial.
What this book covers Chapter 1, Understanding the Architecture of React Applications, explores how to think about applications from an architectural point of view. It starts by covering the importance of good architecture and its benefits. Then, it covers some bad and good practices in React applications. Finally, we will cover the planning of a real React application, an AI Ideas Community Platform, that we will be building throughout the book. Chapter 2, Setup and Project Structure Overview, covers laying out the foundation of the project with all the tools and setup for the application that we will be building. It will introduce us to tools such as React Router, Vite, TypeScript, ESLint, Prettier, and Husky. Finally, it will cover the feature-based project structure for the project, which improves the codebase organization. Chapter 3, Building and Documenting Components, introduces us to component design principles and Shadcn UI, a copy-paste component library built on top of Radix UI primitives. We will cover how to set it up and use it to build reusable components that can be used throughout the application to keep the UI consistent. Finally, we will learn about documenting those components with Storybook. Chapter 4, Routing and Rendering Strategies, dives into React Router in framework mode and different rendering strategies in more depth. First, we will cover the basics such as routing, nested layouts, and data prefetching with loaders. Then, we will explore the different rendering strategies it supports: pre-rendering, SSR, CSR, and hybrid. Finally, we will apply those concepts by building the routes and layouts for our application. Chapter 5, Communicating with the API, walks through how to communicate with the backend API in a type-safe way. We will first learn how to generate TypeScript types from an OpenAPI specification and validate API responses at runtime. Then, we will configure React Query and use it to build the API layer for our application, covering queries, mutations, and cache invalidation. Chapter 6, Managing Application State, teaches how to use the right state management tool for each use case. We will start with local UI state, then move to global state with Zustand. From there, we will look at form state with React Hook Form and Zod, and finish with URL state management for features like filters and search parameters. Chapter 7, Implementing Authentication and Securing the Application, starts by walking through how to implement authentication for our application using cookie-based sessions. Then, it demonstrates how to protect routes and enforce authorization policies for resource ownership. Finally, it covers security best practices such as content sanitization and security headers. Chapter 8, Improving Application Performance, focuses on performance optimization in a React application. It starts by covering how to detect and diagnose performance bottlenecks using the Preface xvi
React DevTools Profiler. Then, it covers a range of optimization techniques including memoization, code splitting with lazy loading, server-side streaming, debouncing, infinite scroll, and optimistic UI updates. Chapter 9, Going International, guides you through setting up internationalization for a React application. We will first cover how to configure react-i18next and organize translations by feature namespace. Then, we will go through key concepts such as server-side language detection, pluralization, variable interpolation, and locale-aware date formatting. Finally, we will build a language switcher component that stores the user's preference in a cookie, which persists across page reloads. Chapter 10, Making the Application Accessible, examines the practices for making your application accessible following WCAG standards. It starts with the POUR principles as a framework for thinking about accessibility. Then, it covers practical techniques such as semantic HTML, skip links, ARIA attributes, live regions for dynamic content announcements, and visible focus styles for keyboard navigation. Chapter 11, Testing the Application, takes a practical approach to testing a React application using the testing trophy strategy. We will cover unit and component testing with Vitest and React Testing Library, focusing on complex isolated logic and UI behavior. Then, we will use Playwright for integration and end-to-end tests, covering route mocking and structuring tests with test steps. Chapter 12, Going to Production, covers the basics of setting up a CI/CD pipeline with GitHub Actions. We will first configure the CI pipeline with parallel jobs for linting, type checking, format checking, and all test tiers. Then, we will set up the CD pipeline to trigger on a successful CI run on the main branch and deploy the application to Render. Chapter 13, Evolving the Application, touches on some advanced topics for taking the application beyond its current state. We will look at using AI to enforce architectural standards, React Server Components, application observability, feature flags, the backend for frontend pattern, and how to scale the codebase with monorepos and microfrontends. To get the most out of this book Previous experience with JavaScript and React and fundamental knowledge of web development will make it a lot easier to follow along with the content of the book. It is also desirable to have some experience with TypeScript and React Router, but it should be possible to follow along without it since we will cover the basics in the book. xvii Preface
Download the example code files This book includes a complete downloadable code bundle containing all the example projects and files used throughout the chapters. We recommend downloading the bundle so you can follow along smoothly and experiment with the examples. Use the bundle as a practical starting point. Modify it, extend it, and apply what you learn by creating your own variations as you progress through the chapters. Get the code bundle If you bought the book directly from Packt: Go to packtpub.com Click your profile picture and select Your Orders Find this book and click Download Code If you bought this book from Amazon or any other channel partner: Go to packtpub.com/unlock or scan the following QR code: Search for this book Sign up or log in to your free Packt account Upload your proof of purchase and download the code bundle locally Usage note: You're free to use and modify this code for personal learning and non-commercial projects. Conventions used There are a number of text conventions used throughout this book. CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: " We could use this same Counter component multiple times on a page 1. 2. 3. 1. 2. 3. 4. Preface xviii
A block of code is set as follows: export default function HomePage() { return ( <div> <h1>Home</h1> <Counter initialValue={0} label="Click Counter" onIncrement={(newValue) => { console.log(`Incremented to ${newValue}`); }} onDecrement={(newValue) => { console.log(`Decremented to ${newValue}`); }} /> </div> ); } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: export default function HomePage() { return ( <div> <h1>Home</h1> <Counter initialValue={0} label="Click Counter" onIncrement={(newValue) => { console.log(`Incremented to ${newValue}`); }} onDecrement={(newValue) => { console.log(`Decremented to ${newValue}`); }} /> </div> ); } xix Preface