Building React Components
Best practices for building reusable, maintainable React components.
When to Apply
Reference these guidelines when:
- - Creating new React components
- Reviewing component structure and API design
- Refactoring components for better reusability
- Implementing component composition patterns
- Designing props interfaces
Core Principles
1. Single Responsibility
Each component should do one thing well. Split large components into smaller, focused pieces.
2. Composition Over Inheritance
Prefer composing components together rather than complex inheritance hierarchies.
CODEBLOCK0
3. Props Design
- - Use TypeScript for props typing
- Keep props interfaces simple and focused
- Prefer many small props over few large objects
- Use children prop for content composition
4. Component Structure
CODEBLOCK1
5. State Management
- - Keep state as close to where it's used as possible
- Lift state up only when necessary
- Consider custom hooks for reusable state logic
Common Patterns
Compound Components
For flexible APIs like Select/Option, Tabs/TabList/Tab/TabPanel.
Render Props
For sharing behavior while keeping rendering control.
Hooks
For sharing stateful logic across components.
Related Skills
- - vercel-react-best-practices
- next-best-practices
- vercel-composition-patterns
构建React组件
构建可复用、可维护的React组件的最佳实践。
适用场景
在以下情况参考这些指南:
- - 创建新的React组件时
- 审查组件结构和API设计时
- 重构组件以提高可复用性时
- 实现组件组合模式时
- 设计props接口时
核心原则
1. 单一职责
每个组件应专注于做好一件事。将大型组件拆分为更小、更专注的模块。
2. 组合优于继承
优先选择组件组合,而非复杂的继承层级。
jsx
// ✅ 推荐:组合
function Page() {
return (
);
}
// ❌ 避免:深层嵌套
function Page() {
return ;
}
3. Props设计
- - 使用TypeScript进行props类型定义
- 保持props接口简洁且专注
- 优先使用多个小型props而非少数大型对象
- 使用children prop进行内容组合
4. 组件结构
tsx
// ✅ 推荐结构
import { FC } from react;
interface Props {
title: string;
children?: React.ReactNode;
}
export const Card: FC = ({ title, children }) => {
return (
{title}
{children}
);
};
5. 状态管理
- - 将状态尽可能保持在离使用位置最近的地方
- 仅在必要时提升状态
- 考虑使用自定义hooks实现可复用的状态逻辑
常见模式
复合组件
适用于Select/Option、Tabs/TabList/Tab/TabPanel等灵活API。
Render Props
用于在保持渲染控制的同时共享行为。
Hooks
用于跨组件共享有状态逻辑。
相关技能
- - vercel-react-best-practices
- next-best-practices
- vercel-composition-patterns