bulletproof-react-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBulletproof React Patterns
Bulletproof React 架构模式
Architecture patterns for building scalable, maintainable React applications. Based on bulletproof-react.
用于构建可扩展、易维护的 React 应用的架构模式。基于 bulletproof-react。
Core References
核心参考
| Topic | Description | Reference |
|---|---|---|
| Project Structure | Feature-based organization, unidirectional architecture, ESLint enforcement | project-structure |
| Components & Styling | Component hierarchy, wrapping 3rd party libs, headless vs styled libraries | components-and-styling |
| API Layer | API client, request declarations, query/mutation hook patterns | api-layer |
| State Management | Component, application, server cache, form, and URL state categories | state-management |
| Error Handling | Error boundaries, API errors, error tracking with Sentry | error-handling |
| Testing | Unit, integration, e2e strategies with Vitest, Testing Library, Playwright, MSW | testing |
| Project Standards | ESLint, Prettier, TypeScript, Husky, absolute imports, file naming | project-standards |
| Security | Authentication, token storage, XSS prevention, RBAC/PBAC authorization | security |
| Performance | Code splitting, data prefetching, state optimization, children pattern | performance |
| 主题 | 描述 | 参考 |
|---|---|---|
| 项目结构 | 基于功能的组织方式、单向架构、ESLint 约束 | project-structure |
| 组件与样式 | 组件层级、封装第三方库、headless 库与 styled 库的取舍 | components-and-styling |
| API 层 | API 客户端、请求声明、query/mutation hook 模式 | api-layer |
| 状态管理 | 组件状态、应用状态、服务器缓存、表单状态和 URL 状态分类 | state-management |
| 错误处理 | Error Boundary、API 错误、使用 Sentry 进行错误追踪 | error-handling |
| 测试 | 使用 Vitest、Testing Library、Playwright、MSW 进行单元、集成和 E2E 测试 | testing |
| 项目规范 | ESLint、Prettier、TypeScript、Husky、绝对路径导入、文件命名 | project-standards |
| 安全 | 身份验证、令牌存储、XSS 防护、RBAC/PBAC 授权 | security |
| 性能 | 代码拆分、数据预取、状态优化、children 模式 | performance |
Project Structure
项目结构
Organize by feature, not by file type:
src/
├── app/ # Application shell (routes, providers, router)
├── assets/ # Static files (images, fonts)
├── components/ # Shared, reusable UI components
├── config/ # Environment variables, constants
├── features/ # Feature-based modules
├── hooks/ # Shared custom hooks
├── lib/ # Pre-configured library wrappers
├── stores/ # Global client state
├── testing/ # Test utilities, MSW handlers, factories
├── types/ # Shared TypeScript types
└── utils/ # Pure utility functions按功能组织,而不是按文件类型组织:
src/
├── app/ # Application shell (routes, providers, router)
├── assets/ # Static files (images, fonts)
├── components/ # Shared, reusable UI components
├── config/ # Environment variables, constants
├── features/ # Feature-based modules
├── hooks/ # Shared custom hooks
├── lib/ # Pre-configured library wrappers
├── stores/ # Global client state
├── testing/ # Test utilities, MSW handlers, factories
├── types/ # Shared TypeScript types
└── utils/ # Pure utility functionsFeature Modules
功能模块
features/users/
├── api/ # API functions and query hooks
├── components/ # Feature-specific components
├── hooks/ # Feature-specific hooks
├── types/ # Feature-specific types
└── utils/ # Feature-specific utilitiesRules:
- Features should not import from other features. Compose at the app level.
- Code flows one direction: shared → features → app.
- Promote to shared directories only when reused by 2+ features.
- Prefer direct imports over barrel re-exports for Vite tree-shaking.
features/users/
├── api/ # API functions and query hooks
├── components/ # Feature-specific components
├── hooks/ # Feature-specific hooks
├── types/ # Feature-specific types
└── utils/ # Feature-specific utilities规则:
- 功能模块不应导入其他功能模块中的内容,应在 app 层进行组合。
- 代码应单向流动:shared → features → app。
- 只有在内容被 2 个及以上功能复用时,才将其提升到 shared 目录。
- 为实现 Vite tree-shaking,应优先直接导入,而非通过 barrel 文件重新导出。
Component Hierarchy
组件层级
Page Components → route-level, compose features, handle layout
└── Feature Components → feature-specific, business logic
└── UI Components → shared primitives, no business logicPage Components → route-level, compose features, handle layout
└── Feature Components → feature-specific, business logic
└── UI Components → shared primitives, no business logicAPI Layer Pattern
API 层模式
typescript
// Pure API function
function getUsers(params?: GetUsersParams): Promise<UsersResponse> {
return api.get("/users", { params });
}
// Query hook wrapping the API function
function useUsers(params?: GetUsersParams) {
return useQuery({
queryKey: ["users", params],
queryFn: () => getUsers(params),
});
}typescript
// Pure API function
function getUsers(params?: GetUsersParams): Promise<UsersResponse> {
return api.get("/users", { params });
}
// Query hook wrapping the API function
function useUsers(params?: GetUsersParams) {
return useQuery({
queryKey: ["users", params],
queryFn: () => getUsers(params),
});
}State Management Boundaries
状态管理边界
| State Type | Solution | Examples |
|---|---|---|
| Server state | TanStack Query | User data, posts, API responses |
| Client state (global) | Zustand / Jotai | Theme, sidebar open, user preferences |
| Client state (local) | useState / useReducer | Form inputs, toggles, modal open |
| URL state | URL search params / router | Filters, pagination, active tab |
| Form state | React Hook Form | Multi-step forms, validation |
Don't mix server and client state. Never copy query data into .
useState| 状态类型 | 解决方案 | 示例 |
|---|---|---|
| 服务器状态 | TanStack Query | 用户数据、帖子、API 响应 |
| 客户端状态(全局) | Zustand / Jotai | 主题、侧边栏展开状态、用户偏好 |
| 客户端状态(局部) | useState / useReducer | 表单输入、开关、弹窗打开状态 |
| URL 状态 | URL search params / router | 筛选器、分页、当前标签页 |
| 表单状态 | React Hook Form | 多步骤表单、验证 |
不要混合服务器状态和客户端状态。 永远不要将 query 数据复制到 中。
useStateError Hierarchy
错误层级
App Error Boundary → catches unrecoverable crashes
└── Route Error Boundary → catches route-level failures, shows retry
└── Feature Error Boundary → catches feature-specific errorsApp Error Boundary → catches unrecoverable crashes
└── Route Error Boundary → catches route-level failures, shows retry
└── Feature Error Boundary → catches feature-specific errorsTesting Strategy
测试策略
| Layer | Tool | What to Test |
|---|---|---|
| Components | Testing Library | Render output, user interactions, a11y |
| Hooks | renderHook | State changes, side effects |
| API | MSW | Request/response handling, error states |
| Integration | Testing Library + MSW | Full feature flows (render → interact → verify) |
| E2E | Playwright | Critical user journeys |
| 层级 | 工具 | 测试内容 |
|---|---|---|
| 组件 | Testing Library | 渲染输出、用户交互、a11y |
| Hooks | renderHook | 状态变化、副作用 |
| API | MSW | 请求/响应处理、错误状态 |
| 集成 | Testing Library + MSW | 完整功能流程(渲染 → 交互 → 验证) |
| E2E | Playwright | 关键用户旅程 |
Conventions
约定
| Item | Convention | Example |
|---|---|---|
| Components | PascalCase | |
| Hooks | camelCase, | |
| Utilities | camelCase | |
| Types | PascalCase | |
| Constants | UPPER_SNAKE_CASE | |
| Directories | kebab-case | |
| Files | kebab-case | |
| 项目 | 约定 | 示例 |
|---|---|---|
| 组件 | PascalCase | |
| Hooks | camelCase、 | |
| 工具函数 | camelCase | |
| 类型 | PascalCase | |
| 常量 | UPPER_SNAKE_CASE | |
| 目录 | kebab-case | |
| 文件 | kebab-case | |
Imports
导入
Use path aliases to avoid deep relative imports:
typescript
import { Button } from "@/components/ui/button";
import { useUsers } from "@/features/users/api";Configure as the alias in .
@/src/tsconfig.json使用路径别名,避免深层相对路径导入:
typescript
import { Button } from "@/components/ui/button";
import { useUsers } from "@/features/users/api";在 中将 配置为 的别名。
tsconfig.json@/src/