react-code-review
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Code Review
React代码审查
Overview
概述
This skill provides structured, comprehensive code review for React applications. It evaluates code against React 19 best practices, component architecture patterns, hook usage, accessibility standards, and production-readiness criteria. The review produces actionable findings categorized by severity (Critical, Warning, Suggestion) with concrete code examples for improvements.
This skill delegates to the agent for deep architectural analysis when invoked through the agent system.
react-software-architect-review本Skill为React应用提供结构化、全面的代码审查服务。它会依据React 19最佳实践、组件架构模式、Hook使用规范、无障碍标准以及生产就绪标准对代码进行评估。审查结果会生成可执行的发现项,按严重程度(Critical、Warning、Suggestion)分类,并附带具体的代码优化示例。
当通过Agent系统调用时,本Skill会委托Agent进行深度架构分析。
react-software-architect-reviewWhen to Use
使用场景
- Reviewing React components, hooks, and pages before merging
- Validating component composition and reusability patterns
- Checking proper hook usage (useState, useEffect, useMemo, useCallback)
- Reviewing React 19 patterns (use, useOptimistic, useFormStatus, Actions)
- Evaluating state management approaches (local, context, external stores)
- Assessing performance optimization (memoization, code splitting, lazy loading)
- Reviewing accessibility compliance (WCAG, semantic HTML, ARIA)
- Validating TypeScript typing for props, state, and events
- Checking Tailwind CSS and styling patterns
- After implementing new React features or refactoring component architecture
- 合并前审查React组件、Hook和页面
- 验证组件组合与复用模式
- 检查Hook的正确使用(useState、useEffect、useMemo、useCallback)
- 审查React 19模式(use、useOptimistic、useFormStatus、Actions)
- 评估状态管理方案(本地状态、Context、外部状态库)
- 评估性能优化(记忆化、代码分割、懒加载)
- 审查无障碍合规性(WCAG、语义化HTML、ARIA)
- 验证React组件的TypeScript类型定义(Props、状态、事件)
- 检查Tailwind CSS与样式模式
- 实现新React功能或重构组件架构后
Instructions
操作步骤
-
Identify Scope: Determine which React components and hooks are under review. Useto discover
glob/.tsxfiles and.jsxto identify component definitions, hook usage, and context providers.grep -
Analyze Component Architecture: Verify proper component composition — check for single responsibility, appropriate size, and reusability. Look for components that are too large (>200 lines), have too many props (>7), or mix concerns.
-
Review Hook Usage: Validate proper hook usage — check dependency arrays in/
useEffect/useMemo, verify cleanup functions inuseCallback, and identify unnecessary re-renders caused by missing or incorrect memoization.useEffect -
Evaluate State Management: Assess where state lives — check for proper colocation, unnecessary lifting, and appropriate use of Context vs external stores. Verify that server state uses TanStack Query, SWR, or similar libraries rather than manual+
useEffectpatterns.useState -
Check Accessibility: Review semantic HTML usage, ARIA attributes, keyboard navigation, focus management, and screen reader compatibility. Verify that interactive elements are accessible and form inputs have proper labels.
-
Assess Performance: Look for unnecessary re-renders, missingon expensive components, improper use of
React.memo/useCallback, missing code splitting, and large bundle imports.useMemo -
Review TypeScript Integration: Check prop type definitions, event handler typing, generic component patterns, and proper use of utility types. Verify thatis not used where specific types are possible.
any -
Produce Review Report: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
-
确定范围:确定要审查的React组件和Hook。使用查找
glob/.tsx文件,使用.jsx识别组件定义、Hook使用和Context提供者。grep -
分析组件架构:验证组件组合是否合理——检查是否符合单一职责、大小是否合适、是否具备复用性。留意代码行数超过200行、Props数量超过7个或混合多种职责的组件。
-
审查Hook使用:验证Hook的正确使用——检查/
useEffect/useMemo的依赖数组,确认useCallback中的清理函数,识别因缺失或错误记忆化导致的不必要重渲染。useEffect -
评估状态管理:评估状态的存放位置——检查是否合理内聚、是否存在不必要的状态提升、Context与外部状态库的使用是否恰当。验证服务端状态是否使用TanStack Query、SWR或类似库,而非手动的+
useEffect模式。useState -
检查无障碍性:审查语义化HTML使用、ARIA属性、键盘导航、焦点管理以及屏幕阅读器兼容性。确保交互元素可访问,表单输入有合适的标签。
-
评估性能:查找不必要的重渲染、昂贵组件缺失、
React.memo/useCallback使用不当、缺失代码分割以及大体积包导入的问题。useMemo -
审查TypeScript集成:检查Props类型定义、事件处理函数类型、泛型组件模式以及工具类型的正确使用。验证是否在可以使用具体类型的场景下避免了的使用。
any -
生成审查报告:生成结构化报告,包含按严重程度分类的发现项(Critical、Warning、Suggestion)、正向观察结果以及附带代码示例的优先级优化建议。
Examples
示例
Example 1: Hook Dependency Issues
示例1:Hook依赖问题
tsx
// ❌ Bad: Missing dependency causes stale closure
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, []); // Missing userId in dependency array
return <div>{user?.name}</div>;
}
// ✅ Good: Proper dependencies with cleanup
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
let cancelled = false;
fetchUser(userId).then((data) => {
if (!cancelled) setUser(data);
});
return () => { cancelled = true; };
}, [userId]);
return <div>{user?.name}</div>;
}
// ✅ Better: Use TanStack Query for server state
function UserProfile({ userId }: { userId: string }) {
const { data: user, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
});
if (isLoading) return <Skeleton />;
return <div>{user?.name}</div>;
}tsx
// ❌ 不良示例:缺失依赖导致闭包过时
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, []); // 依赖数组中缺失userId
return <div>{user?.name}</div>;
}
// ✅ 良好示例:依赖正确并包含清理函数
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
let cancelled = false;
fetchUser(userId).then((data) => {
if (!cancelled) setUser(data);
});
return () => { cancelled = true; };
}, [userId]);
return <div>{user?.name}</div>;
}
// ✅ 更优示例:使用TanStack Query管理服务端状态
function UserProfile({ userId }: { userId: string }) {
const { data: user, isLoading } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetchUser(userId),
});
if (isLoading) return <Skeleton />;
return <div>{user?.name}</div>;
}Example 2: Component Composition
示例2:组件组合
tsx
// ❌ Bad: Monolithic component mixing data fetching, filtering, and rendering
function Dashboard() {
const [users, setUsers] = useState([]);
const [filter, setFilter] = useState('');
useEffect(() => { /* fetch + filter + sort all in one */ }, [filter]);
return <div>{/* 200+ lines of mixed concerns */}</div>;
}
// ✅ Good: Composed from focused components with custom hooks
function Dashboard() {
return (
<div>
<UserFilters />
<Suspense fallback={<TableSkeleton />}>
<UserTable />
</Suspense>
<UserPagination />
</div>
);
}tsx
// ❌ 不良示例:单体组件混合数据获取、过滤与渲染
function Dashboard() {
const [users, setUsers] = useState([]);
const [filter, setFilter] = useState('');
useEffect(() => { /* 数据获取+过滤+排序全部混在一起 */ }, [filter]);
return <div>{/* 200多行混合多种职责的代码 */}</div>;
}
// ✅ 良好示例:由专注单一职责的组件和自定义Hook组合而成
function Dashboard() {
return (
<div>
<UserFilters />
<Suspense fallback={<TableSkeleton />}>
<UserTable />
</Suspense>
<UserPagination />
</div>
);
}Example 3: Accessibility Review
示例3:无障碍审查
tsx
// ❌ Bad: Inaccessible interactive elements
function Menu({ items }: { items: MenuItem[] }) {
const [open, setOpen] = useState(false);
return (
<div>
<div onClick={() => setOpen(!open)}>Menu</div>
{open && (
<div>
{items.map(item => (
<div key={item.id} onClick={() => navigate(item.path)}>
{item.label}
</div>
))}
</div>
)}
</div>
);
}
// ✅ Good: Accessible with proper semantics and keyboard support
function Menu({ items }: { items: MenuItem[] }) {
const [open, setOpen] = useState(false);
return (
<nav aria-label="Main navigation">
<button
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-controls="menu-list"
>
Menu
</button>
{open && (
<ul id="menu-list" role="menu">
{items.map(item => (
<li key={item.id} role="menuitem">
<a href={item.path}>{item.label}</a>
</li>
))}
</ul>
)}
</nav>
);
}tsx
// ❌ 不良示例:交互元素无法访问
function Menu({ items }: { items: MenuItem[] }) {
const [open, setOpen] = useState(false);
return (
<div>
<div onClick={() => setOpen(!open)}>Menu</div>
{open && (
<div>
{items.map(item => (
<div key={item.id} onClick={() => navigate(item.path)}>
{item.label}
</div>
))}
</div>
)}
</div>
);
}
// ✅ 良好示例:具备正确语义和键盘支持的可访问组件
function Menu({ items }: { items: MenuItem[] }) {
const [open, setOpen] = useState(false);
return (
<nav aria-label="Main navigation">
<button
onClick={() => setOpen(!open)}
aria-expanded={open}
aria-controls="menu-list"
>
Menu
</button>
{open && (
<ul id="menu-list" role="menu">
{items.map(item => (
<li key={item.id} role="menuitem">
<a href={item.path}>{item.label}</a>
</li>
))}
</ul>
)}
</nav>
);
}Example 4: Performance Optimization
示例4:性能优化
tsx
// ❌ Bad: Unstable callback recreated every render causes child re-renders
{filtered.map(product => (
<ProductCard
key={product.id}
product={product}
onSelect={() => console.log(product.id)} // New function each render
/>
))}
// ✅ Good: Stable callback + memoized child
const handleSelect = useCallback((id: string) => {
console.log(id);
}, []);
const filtered = useMemo(
() => products.filter(p => p.name.toLowerCase().includes(search.toLowerCase())),
[products, search]
);
{filtered.map(product => (
<ProductCard key={product.id} product={product} onSelect={handleSelect} />
))}
const ProductCard = memo(function ProductCard({ product, onSelect }: Props) {
return <div onClick={() => onSelect(product.id)}>{product.name}</div>;
});tsx
// ❌ 不良示例:不稳定的回调函数每次渲染都会重建,导致子组件重渲染
{filtered.map(product => (
<ProductCard
key={product.id}
product={product}
onSelect={() => console.log(product.id)} // 每次渲染都会创建新函数
/>
))}
// ✅ 良好示例:稳定的回调函数 + 记忆化子组件
const handleSelect = useCallback((id: string) => {
console.log(id);
}, []);
const filtered = useMemo(
() => products.filter(p => p.name.toLowerCase().includes(search.toLowerCase())),
[products, search]
);
{filtered.map(product => (
<ProductCard key={product.id} product={product} onSelect={handleSelect} />
))}
const ProductCard = memo(function ProductCard({ product, onSelect }: Props) {
return <div onClick={() => onSelect(product.id)}>{product.name}</div>;
});Example 5: TypeScript Props Review
示例5:TypeScript Props审查
tsx
// ❌ Bad: Loose typing and missing prop definitions
function Card({ data, onClick, children, ...rest }: any) {
return (
<div onClick={onClick} {...rest}>
<h2>{data.title}</h2>
{children}
</div>
);
}
// ✅ Good: Strict typing with proper interfaces
interface CardProps extends React.ComponentPropsWithoutRef<'article'> {
title: string;
description?: string;
variant?: 'default' | 'outlined' | 'elevated';
onAction?: (event: React.MouseEvent<HTMLButtonElement>) => void;
children: React.ReactNode;
}
function Card({
title,
description,
variant = 'default',
onAction,
children,
className,
...rest
}: CardProps) {
return (
<article className={cn('card', `card--${variant}`, className)} {...rest}>
<h2>{title}</h2>
{description && <p>{description}</p>}
{children}
{onAction && <button onClick={onAction}>Action</button>}
</article>
);
}tsx
// ❌ 不良示例:松散的类型定义和缺失的Props定义
function Card({ data, onClick, children, ...rest }: any) {
return (
<div onClick={onClick} {...rest}>
<h2>{data.title}</h2>
{children}
</div>
);
}
// ✅ 良好示例:具备正确接口的严格类型定义
interface CardProps extends React.ComponentPropsWithoutRef<'article'> {
title: string;
description?: string;
variant?: 'default' | 'outlined' | 'elevated';
onAction?: (event: React.MouseEvent<HTMLButtonElement>) => void;
children: React.ReactNode;
}
function Card({
title,
description,
variant = 'default',
onAction,
children,
className,
...rest
}: CardProps) {
return (
<article className={cn('card', `card--${variant}`, className)} {...rest}>
<h2>{title}</h2>
{description && <p>{description}</p>}
{children}
{onAction && <button onClick={onAction}>Action</button>}
</article>
);
}Review Output Format
审查输出格式
Structure all code review findings as follows:
所有代码审查发现项需按以下结构组织:
1. Summary
1. 摘要
Brief overview with an overall quality score (1-10) and key observations.
简短概述,包含整体质量评分(1-10分)和关键观察结果。
2. Critical Issues (Must Fix)
2. 严重问题(必须修复)
Issues causing bugs, security vulnerabilities, or broken functionality.
会导致Bug、安全漏洞或功能故障的问题。
3. Warnings (Should Fix)
3. 警告(建议修复)
Issues that violate best practices, cause performance problems, or reduce maintainability.
违反最佳实践、导致性能问题或降低可维护性的问题。
4. Suggestions (Consider Improving)
4. 建议(考虑优化)
Improvements for code organization, accessibility, or developer experience.
针对代码组织、无障碍性或开发者体验的优化建议。
5. Positive Observations
5. 正向观察结果
Well-implemented patterns and good practices to acknowledge.
值得肯定的优秀实现模式和最佳实践。
6. Recommendations
6. 优化建议
Prioritized next steps with code examples for the most impactful improvements.
优先级排序的后续步骤,附带影响最大的优化代码示例。
Best Practices
最佳实践
- Keep components focused — single responsibility, under 200 lines
- Colocate state with the components that use it
- Use custom hooks to extract reusable logic from components
- Apply only when measured re-render cost justifies it
React.memo - Use TanStack Query or SWR for server state instead of +
useEffectuseState - Always include cleanup functions in when subscribing to external resources
useEffect - Write semantic HTML first, add ARIA only when native semantics are insufficient
- Use TypeScript strict mode and avoid in component props
any - Implement error boundaries for graceful failure handling
- Prefer composition over conditional rendering complexity
- 保持组件专注——单一职责,代码行数控制在200行以内
- 将状态与使用它的组件内聚
- 使用自定义Hook提取组件中的可复用逻辑
- 仅当测量到重渲染成本较高时才使用
React.memo - 使用TanStack Query或SWR管理服务端状态,而非+
useEffectuseState - 当订阅外部资源时,中必须包含清理函数
useEffect - 优先使用语义化HTML,仅当原生语义不足时再添加ARIA属性
- 使用TypeScript严格模式,避免在组件Props中使用
any - 实现错误边界以优雅处理故障
- 优先使用组件组合而非复杂的条件渲染
Constraints and Warnings
约束与注意事项
- Respect the project's React version — avoid suggesting React 19 features for older versions
- Do not enforce a specific state management library unless the project has standardized on one
- Memoization is not always beneficial — only suggest it when re-render impact is measurable
- Accessibility recommendations should follow WCAG 2.1 AA as the baseline
- Focus on high-confidence issues — avoid false positives on subjective style choices
- Do not suggest rewriting working components without clear, measurable benefit
- 尊重项目的React版本——避免为旧版本项目建议React 19特性
- 除非项目已标准化使用某一状态管理库,否则不要强制使用特定库
- 记忆化并非总是有益的——仅当可测量到重渲染影响时才建议使用
- 无障碍建议应以WCAG 2.1 AA为基准
- 专注于高可信度问题——避免对主观风格选择给出错误的阳性判断
- 若无明确、可测量的收益,不要建议重写可正常工作的组件
References
参考资料
See the directory for detailed review checklists and pattern documentation:
references/- — React hooks best practices and common mistakes
references/hooks-patterns.md - — Component composition and design patterns
references/component-architecture.md - — Accessibility checklist and ARIA patterns for React
references/accessibility.md
请查看目录获取详细的审查清单和模式文档:
references/- — React Hook最佳实践与常见错误
references/hooks-patterns.md - — 组件组合与设计模式
references/component-architecture.md - — React无障碍检查清单与ARIA模式
references/accessibility.md