react-refactor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Refactor Best Practices
React重构最佳实践
Architectural refactoring guide for React applications. Contains 40 rules across 7 categories, prioritized by impact from critical (component and state architecture) to incremental (refactoring safety).
React应用架构重构指南,包含7个类别共40条规则,按影响优先级排序,从关键(组件与状态架构)到渐进式(重构安全性)。
When to Apply
适用场景
- Refactoring existing React codebases or planning large-scale restructuring
- Reviewing PRs for architectural issues and code smells
- Decomposing oversized components into focused units
- Extracting reusable hooks from component logic
- Improving testability of React code
- Reducing coupling between feature modules
- 重构现有React代码库或规划大规模架构调整
- 审查PR中的架构问题与代码异味
- 将过大的组件拆分为职责单一的单元
- 从组件逻辑中提取可复用的Hook
- 提升React代码的可测试性
- 降低功能模块间的耦合度
Rule Categories
规则类别
| Category | Impact | Rules | Key Topics |
|---|---|---|---|
| Component Architecture | CRITICAL | 8 | Compound components, headless pattern, composition over props, client boundaries |
| State Architecture | CRITICAL | 7 | Colocation, state machines, URL state, derived values |
| Hook Patterns | HIGH | 6 | Single responsibility, naming, dependency stability, composition |
| Component Decomposition | HIGH | 6 | Scroll test, extraction by change reason, view/logic separation |
| Coupling & Cohesion | MEDIUM | 4 | Dependency injection, circular deps, stable imports, barrel-free |
| Data & Side Effects | MEDIUM | 4 | Server-first fetch, TanStack Query, error boundaries |
| Refactoring Safety | LOW-MEDIUM | 5 | Characterization tests, behavior testing, integration tests |
| 类别 | 影响级别 | 规则数量 | 核心主题 |
|---|---|---|---|
| 组件架构 | 关键 | 8 | 复合组件、无头组件模式、组合优于传参、客户端边界 |
| 状态架构 | 关键 | 7 | 就近放置、状态机、URL状态、派生值 |
| Hook模式 | 高 | 6 | 单一职责、命名规范、依赖稳定性、组合 |
| 组件拆分 | 高 | 6 | 滚动测试、按变更原因提取、视图/逻辑分离 |
| 耦合与内聚 | 中 | 4 | 依赖注入、循环依赖、稳定导入、无桶文件 |
| 数据与副作用 | 中 | 4 | 优先服务端请求、TanStack Query、错误边界 |
| 重构安全性 | 低-中 | 5 | 特征测试、行为测试、集成测试 |
Quick Reference
快速参考
Critical patterns — get these right first:
- Use compound components instead of props explosion
- Colocate state with the components that use it
- Use state machines for complex UI workflows
- Separate container logic from presentational components
Common mistakes — avoid these anti-patterns:
- Lifting state to App when only one component reads it
- Using context for rapidly-changing values
- Monolithic hooks that fetch + transform + cache
- Testing implementation details instead of behavior
关键模式 — 优先确保这些正确:
- 使用复合组件替代大量传参
- 将状态放置在使用它的组件附近
- 为复杂UI流程使用状态机
- 将容器逻辑与展示组件分离
常见错误 — 避免这些反模式:
- 当只有一个组件读取状态时,将状态提升到App组件
- 使用context存储频繁变化的值
- 编写同时处理请求、转换与缓存的巨型Hook
- 测试实现细节而非行为
Table of Contents
目录
- Component Architecture — CRITICAL
- 1.1 Apply Interface Segregation to Component Props — CRITICAL (prevents 30-50% of unnecessary re-renders)
- 1.2 Colocate Files by Feature Instead of Type — CRITICAL (reduces cross-directory navigation by 70%)
- 1.3 Convert Render Props to Custom Hooks — CRITICAL (eliminates 2-4 levels of nesting)
- 1.4 Extract Headless Components for Logic Reuse — CRITICAL (5x more reuse scenarios)
- 1.5 Prefer Composition Over Props Explosion — CRITICAL (reduces prop count by 50-70%)
- 1.6 Separate Container Logic from Presentational Components — CRITICAL (enables independent testing)
- 1.7 Use Compound Components for Implicit State Sharing — CRITICAL (reduces API surface by 60%)
- 1.8 Push Client Boundaries to Leaf Components — HIGH (keeps 60-80% server-rendered)
- State Architecture — CRITICAL
- 2.1 Colocate State with Components That Use It — CRITICAL (reduces prop passing by 60%)
- 2.2 Derive Values Instead of Syncing State — CRITICAL (eliminates double-render cycle)
- 2.3 Lift State Only When Multiple Components Read It — CRITICAL (eliminates unnecessary parent re-renders)
- 2.4 Use Context for Rarely-Changing Values Only — CRITICAL (5-50x fewer re-renders)
- 2.5 Use State Machines for Complex UI Workflows — CRITICAL (reduces valid states from 2^n to N)
- 2.6 Use URL Parameters as State for Shareable Views — CRITICAL (enables deep linking and sharing)
- 2.7 Use useReducer for Multi-Field State Transitions — CRITICAL (eliminates impossible states)
- Hook Patterns — HIGH
- 3.1 Avoid Object and Array Dependencies in Custom Hooks — HIGH (prevents effect re-execution every render)
- 3.2 Compose Hooks Instead of Nesting Them — HIGH (flattens dependency graph)
- 3.3 Extract Logic into Custom Hooks When Behavior Is Nameable — HIGH (40-60% shorter components)
- 3.4 Follow Hook Naming Conventions for Discoverability — HIGH (reduces navigation time by 40%)
- 3.5 Keep Custom Hooks to a Single Responsibility — HIGH (3x easier to test)
- 3.6 Stabilize Hook Dependencies with Refs and Callbacks — HIGH (prevents infinite loops)
- Component Decomposition — HIGH
- 4.1 Apply the Scroll Test to Identify Oversized Components — HIGH (3x faster code review)
- 4.2 Complete Component Extraction Without Half-Measures — HIGH (enables independent testing and reuse)
- 4.3 Extract Components by Independent Change Reasons — HIGH (70% fewer files touched per change)
- 4.4 Extract Pure Functions from Component Bodies — HIGH (10x faster unit tests)
- 4.5 Inline Premature Abstractions Before Re-Extracting — HIGH (40-60% simpler code)
- 4.6 Separate View Layer from Business Logic — HIGH (5x faster test suite)
- Coupling & Cohesion — MEDIUM
- 5.1 Break Circular Dependencies with Intermediate Modules — MEDIUM (eliminates undefined-at-import-time bugs)
- 5.2 Import from Stable Public API Surfaces Only — MEDIUM (enables internal refactoring)
- 5.3 Use Barrel-Free Feature Modules for Clean Dependencies — MEDIUM (200-800ms build reduction)
- 5.4 Use Dependency Injection for External Services — MEDIUM (3x faster test setup)
- Data & Side Effects — MEDIUM
- 6.1 Fetch Data on the Server by Default — MEDIUM (reduces client JS by 30-60%)
- 6.2 Place Error Boundaries at Data Fetch Granularity — MEDIUM (errors isolated to affected section)
- 6.3 Use Context Module Pattern for Action Colocation — MEDIUM (centralizes data mutations)
- 6.4 Use TanStack Query for Client-Side Server State — MEDIUM (eliminates 80% of fetch boilerplate)
- Refactoring Safety — LOW-MEDIUM
- 7.1 Avoid Snapshot Tests for Refactored Components — LOW-MEDIUM (eliminates false test failures)
- 7.2 Extract Pure Functions to Increase Testability — LOW-MEDIUM (10x faster test execution)
- 7.3 Prefer Integration Tests for Component Verification — LOW-MEDIUM (catches 40% more bugs)
- 7.4 Test Component Behavior Not Implementation Details — LOW-MEDIUM (5x fewer test updates)
- 7.5 Write Characterization Tests Before Refactoring — LOW-MEDIUM (catches 90% of unintended changes)
- 组件架构 — 关键
- 1.1 对组件Props应用接口隔离原则 — 关键(减少30-50%不必要的重渲染)
- 1.2 按功能而非类型归置文件 — 关键(减少70%跨目录导航)
- 1.3 将渲染属性转换为自定义Hook — 关键(减少2-4层嵌套)
- 1.4 提取无头组件以复用逻辑 — 关键(复用场景提升5倍)
- 1.5 优先使用组合而非大量传参 — 关键(减少50-70%的Props数量)
- 1.6 分离容器逻辑与展示组件 — 关键(支持独立测试)
- 1.7 使用复合组件实现隐式状态共享 — 关键(减少60%的API表面积)
- 1.8 将客户端边界下推到叶子组件 — 高(保持60-80%的服务端渲染比例)
- 状态架构 — 关键
- 2.1 将状态放置在使用它的组件附近 — 关键(减少60%的Props传递)
- 2.2 派生值而非同步状态 — 关键(消除双重渲染周期)
- 2.3 仅当多个组件需要时才提升状态 — 关键(消除不必要的父组件重渲染)
- 2.4 仅使用context存储极少变化的值 — 关键(减少5-50倍的重渲染)
- 2.5 为复杂UI流程使用状态机 — 关键(将有效状态从2^n减少到N)
- 2.6 使用URL参数作为可分享视图的状态 — 关键(支持深度链接与分享)
- 2.7 使用useReducer处理多字段状态转换 — 关键(消除不可能的状态)
- Hook模式 — 高
- 3.1 在自定义Hook中避免对象与数组依赖 — 高(防止每次渲染都重新执行副作用)
- 3.2 组合Hook而非嵌套Hook — 高(扁平化依赖图)
- 3.3 当逻辑可命名时提取为自定义Hook — 高(组件代码缩短40-60%)
- 3.4 遵循Hook命名规范以提升可发现性 — 高(减少40%的导航时间)
- 3.5 保持自定义Hook的单一职责 — 高(测试难度降低3倍)
- 3.6 使用Ref与回调稳定Hook依赖 — 高(防止无限循环)
- 组件拆分 — 高
- 4.1 使用滚动测试识别过大的组件 — 高(代码审查速度提升3倍)
- 4.2 完整提取组件,不做折中 — 高(支持独立测试与复用)
- 4.3 按独立变更原因提取组件 — 高(每次变更涉及的文件减少70%)
- 4.4 从组件体中提取纯函数 — 高(单元测试速度提升10倍)
- 4.5 内联过早的抽象后再重新提取 — 高(代码复杂度降低40-60%)
- 4.6 分离视图层与业务逻辑 — 高(测试套件速度提升5倍)
- 耦合与内聚 — 中
- 5.1 使用中间模块打破循环依赖 — 中(消除导入时未定义的bug)
- 5.2 仅从稳定的公共API表面导入 — 中(支持内部重构)
- 5.3 使用无桶文件的功能模块以保持依赖清晰 — 中(构建时间减少200-800ms)
- 5.4 对外部服务使用依赖注入 — 中(测试设置速度提升3倍)
- 数据与副作用 — 中
- 6.1 默认在服务端请求数据 — 中(减少30-60%的客户端JS体积)
- 6.2 在数据请求粒度上设置错误边界 — 中(错误被隔离到受影响的区域)
- 6.3 使用Context模块模式归置操作 — 中(集中管理数据变更)
- 6.4 使用TanStack Query管理客户端侧服务端状态 — 中(减少80%的请求样板代码)
- 重构安全性 — 低-中
- 7.1 避免为重构后的组件使用快照测试 — 低-中(消除测试假阳性失败)
- 7.2 提取纯函数以提升可测试性 — 低-中(测试执行速度提升10倍)
- 7.3 优先使用集成测试验证组件 — 低-中(多捕捉40%的bug)
- 7.4 测试组件行为而非实现细节 — 低-中(测试更新次数减少5倍)
- 7.5 在重构前编写特征测试 — 低-中(捕捉90%的意外变更)
References
参考资料
Related Skills
相关技能
- For React 19 API best practices, see skill
react - For application performance optimization, see skill
react-optimise - For client-side form handling, see skill
react-hook-form
- 关于React 19 API最佳实践,请查看技能
react - 关于应用性能优化,请查看技能
react-optimise - 关于客户端表单处理,请查看技能
react-hook-form