React Code Review
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 react-software-architect-review agent for deep architectural analysis when invoked through the agent system.
When 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
Instructions
Identify Scope: Determine which React components and hooks are under review. Use glob to discover .tsx/.jsx files and grep to identify component definitions, hook usage, and context providers.
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/useCallback, verify cleanup functions in useEffect, and identify unnecessary re-renders caused by missing or incorrect memoization.
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 useEffect + useState patterns.
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, missing React.memo on expensive components, improper use of useCallback/useMemo, missing code splitting, and large bundle imports.
Review TypeScript Integration: Check prop type definitions, event handler typing, generic component patterns, and proper use of utility types. Verify that any is not used where specific types are possible.
Produce Review Report: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
Examples
Example 1: Hook Dependency Issues
// ❌ 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>;
}
Example 2: Component Composition
// ❌ 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>
);
}
Example 3: Accessibility Review
// ❌ Bad: Inaccessible interactive elements
function Menu({ items }: { items: MenuItem[] }) {
const [open, setOpen] = useState(false);
return (
<div>
<div => setOpen(!open)}>Menu</div>
{open && (
<div>
{items.map(item => (
<div key={item.id} => 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
=> 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
// ❌ Bad: Unstable callback recreated every render causes child re-renders
{filtered.map(product => (
<ProductCard
key={product.id}
product={product}
=> 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} />
))}
const ProductCard = memo(function ProductCard({ product, onSelect }: Props) {
return <div => onSelect(product.id)}>{product.name}</div>;
});
Example 5: TypeScript Props Review
// ❌ Bad: Loose typing and missing prop definitions
function Card({ data, onClick, children, ...rest }: any) {
return (
<div {...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
</article>
);
}
Review Output Format
Structure all code review findings as follows:
1. Summary
Brief overview with an overall quality score (1-10) and key observations.
2. Critical Issues (Must Fix)
Issues causing bugs, security vulnerabilities, or broken functionality.
3. Warnings (Should Fix)
Issues that violate best practices, cause performance problems, or reduce maintainability.
4. Suggestions (Consider Improving)
Improvements for code organization, accessibility, or developer experience.
5. Positive Observations
Well-implemented patterns and good practices to acknowledge.
6. Recommendations
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
React.memo only when measured re-render cost justifies it
- Use TanStack Query or SWR for server state instead of
useEffect + useState
- Always include cleanup functions in
useEffect when subscribing to external resources
- Write semantic HTML first, add ARIA only when native semantics are insufficient
- Use TypeScript strict mode and avoid
any in component props
- Implement error boundaries for graceful failure handling
- Prefer composition over conditional rendering complexity
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
References
See the references/ directory for detailed review checklists and pattern documentation:
references/hooks-patterns.md — React hooks best practices and common mistakes
references/component-architecture.md — Component composition and design patterns
references/accessibility.md — Accessibility checklist and ARIA patterns for React
1---2name: react-code-review3description: Provides comprehensive code review capability for React applications, validates component architecture, hooks usage, React 19 patterns, state management, performance optimization, accessibility compliance, and TypeScript integration. Use when reviewing React code changes, before merging pull requests, after implementing new features, or for component architecture validation. Triggers on "review React code", "React code review", "check my React components".4allowed-tools: Read, Edit, Grep, Glob, Bash5metadata:6 source: https://skillmd.com/skills/levalencia/react-code-review7---89# React Code Review1011## Overview1213This 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.1415This skill delegates to the `react-software-architect-review` agent for deep architectural analysis when invoked through the agent system.1617## When to Use1819- Reviewing React components, hooks, and pages before merging20- Validating component composition and reusability patterns21- Checking proper hook usage (useState, useEffect, useMemo, useCallback)22- Reviewing React 19 patterns (use, useOptimistic, useFormStatus, Actions)23- Evaluating state management approaches (local, context, external stores)24- Assessing performance optimization (memoization, code splitting, lazy loading)25- Reviewing accessibility compliance (WCAG, semantic HTML, ARIA)26- Validating TypeScript typing for props, state, and events27- Checking Tailwind CSS and styling patterns28- After implementing new React features or refactoring component architecture2930## Instructions31321. **Identify Scope**: Determine which React components and hooks are under review. Use `glob` to discover `.tsx`/`.jsx` files and `grep` to identify component definitions, hook usage, and context providers.33342. **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.35363. **Review Hook Usage**: Validate proper hook usage — check dependency arrays in `useEffect`/`useMemo`/`useCallback`, verify cleanup functions in `useEffect`, and identify unnecessary re-renders caused by missing or incorrect memoization.37384. **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 `useEffect` + `useState` patterns.39405. **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.41426. **Assess Performance**: Look for unnecessary re-renders, missing `React.memo` on expensive components, improper use of `useCallback`/`useMemo`, missing code splitting, and large bundle imports.43447. **Review TypeScript Integration**: Check prop type definitions, event handler typing, generic component patterns, and proper use of utility types. Verify that `any` is not used where specific types are possible.45468. **Produce Review Report**: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.4748## Examples4950### Example 1: Hook Dependency Issues5152```tsx53// ❌ Bad: Missing dependency causes stale closure54function UserProfile({ userId }: { userId: string }) {55 const [user, setUser] = useState<User | null>(null);5657 useEffect(() => {58 fetchUser(userId).then(setUser);59 }, []); // Missing userId in dependency array6061 return <div>{user?.name}</div>;62}6364// ✅ Good: Proper dependencies with cleanup65function UserProfile({ userId }: { userId: string }) {66 const [user, setUser] = useState<User | null>(null);6768 useEffect(() => {69 let cancelled = false;70 fetchUser(userId).then((data) => {71 if (!cancelled) setUser(data);72 });73 return () => { cancelled = true; };74 }, [userId]);7576 return <div>{user?.name}</div>;77}7879// ✅ Better: Use TanStack Query for server state80function UserProfile({ userId }: { userId: string }) {81 const { data: user, isLoading } = useQuery({82 queryKey: ['user', userId],83 queryFn: () => fetchUser(userId),84 });8586 if (isLoading) return <Skeleton />;87 return <div>{user?.name}</div>;88}89```9091### Example 2: Component Composition9293```tsx94// ❌ Bad: Monolithic component mixing data fetching, filtering, and rendering95function Dashboard() {96 const [users, setUsers] = useState([]);97 const [filter, setFilter] = useState('');98 useEffect(() => { /* fetch + filter + sort all in one */ }, [filter]);99 return <div>{/* 200+ lines of mixed concerns */}</div>;100}101102// ✅ Good: Composed from focused components with custom hooks103function Dashboard() {104 return (105 <div>106 <UserFilters />107 <Suspense fallback={<TableSkeleton />}>108 <UserTable />109 </Suspense>110 <UserPagination />111 </div>112 );113}114```115116### Example 3: Accessibility Review117118```tsx119// ❌ Bad: Inaccessible interactive elements120function Menu({ items }: { items: MenuItem[] }) {121 const [open, setOpen] = useState(false);122 return (123 <div>124 <div onClick={() => setOpen(!open)}>Menu</div>125 {open && (126 <div>127 {items.map(item => (128 <div key={item.id} onClick={() => navigate(item.path)}>129 {item.label}130 </div>131 ))}132 </div>133 )}134 </div>135 );136}137138// ✅ Good: Accessible with proper semantics and keyboard support139function Menu({ items }: { items: MenuItem[] }) {140 const [open, setOpen] = useState(false);141 return (142 <nav aria-label="Main navigation">143 <button144 onClick={() => setOpen(!open)}145 aria-expanded={open}146 aria-controls="menu-list"147 >148 Menu149 </button>150 {open && (151 <ul id="menu-list" role="menu">152 {items.map(item => (153 <li key={item.id} role="menuitem">154 <a href={item.path}>{item.label}</a>155 </li>156 ))}157 </ul>158 )}159 </nav>160 );161}162```163164### Example 4: Performance Optimization165166```tsx167// ❌ Bad: Unstable callback recreated every render causes child re-renders168{filtered.map(product => (169 <ProductCard170 key={product.id}171 product={product}172 onSelect={() => console.log(product.id)} // New function each render173 />174))}175176// ✅ Good: Stable callback + memoized child177const handleSelect = useCallback((id: string) => {178 console.log(id);179}, []);180181const filtered = useMemo(182 () => products.filter(p => p.name.toLowerCase().includes(search.toLowerCase())),183 [products, search]184);185186{filtered.map(product => (187 <ProductCard key={product.id} product={product} onSelect={handleSelect} />188))}189190const ProductCard = memo(function ProductCard({ product, onSelect }: Props) {191 return <div onClick={() => onSelect(product.id)}>{product.name}</div>;192});193```194195### Example 5: TypeScript Props Review196197```tsx198// ❌ Bad: Loose typing and missing prop definitions199function Card({ data, onClick, children, ...rest }: any) {200 return (201 <div onClick={onClick} {...rest}>202 <h2>{data.title}</h2>203 {children}204 </div>205 );206}207208// ✅ Good: Strict typing with proper interfaces209interface CardProps extends React.ComponentPropsWithoutRef<'article'> {210 title: string;211 description?: string;212 variant?: 'default' | 'outlined' | 'elevated';213 onAction?: (event: React.MouseEvent<HTMLButtonElement>) => void;214 children: React.ReactNode;215}216217function Card({218 title,219 description,220 variant = 'default',221 onAction,222 children,223 className,224 ...rest225}: CardProps) {226 return (227 <article className={cn('card', `card--${variant}`, className)} {...rest}>228 <h2>{title}</h2>229 {description && <p>{description}</p>}230 {children}231 {onAction && <button onClick={onAction}>Action</button>}232 </article>233 );234}235```236237## Review Output Format238239Structure all code review findings as follows:240241### 1. Summary242Brief overview with an overall quality score (1-10) and key observations.243244### 2. Critical Issues (Must Fix)245Issues causing bugs, security vulnerabilities, or broken functionality.246247### 3. Warnings (Should Fix)248Issues that violate best practices, cause performance problems, or reduce maintainability.249250### 4. Suggestions (Consider Improving)251Improvements for code organization, accessibility, or developer experience.252253### 5. Positive Observations254Well-implemented patterns and good practices to acknowledge.255256### 6. Recommendations257Prioritized next steps with code examples for the most impactful improvements.258259## Best Practices260261- Keep components focused — single responsibility, under 200 lines262- Colocate state with the components that use it263- Use custom hooks to extract reusable logic from components264- Apply `React.memo` only when measured re-render cost justifies it265- Use TanStack Query or SWR for server state instead of `useEffect` + `useState`266- Always include cleanup functions in `useEffect` when subscribing to external resources267- Write semantic HTML first, add ARIA only when native semantics are insufficient268- Use TypeScript strict mode and avoid `any` in component props269- Implement error boundaries for graceful failure handling270- Prefer composition over conditional rendering complexity271272## Constraints and Warnings273274- Respect the project's React version — avoid suggesting React 19 features for older versions275- Do not enforce a specific state management library unless the project has standardized on one276- Memoization is not always beneficial — only suggest it when re-render impact is measurable277- Accessibility recommendations should follow WCAG 2.1 AA as the baseline278- Focus on high-confidence issues — avoid false positives on subjective style choices279- Do not suggest rewriting working components without clear, measurable benefit280281## References282283See the `references/` directory for detailed review checklists and pattern documentation:284- `references/hooks-patterns.md` — React hooks best practices and common mistakes285- `references/component-architecture.md` — Component composition and design patterns286- `references/accessibility.md` — Accessibility checklist and ARIA patterns for React