react-patterns
React组件模式,包括函数组件、hooks、状态管理、API集成、加载/错误状态和事件处理器。在创建或审查React组件时使用。
📖 中文导读:React组件模式,包括函数组件、hooks、状态管理、API集成、加载/错误状态和事件处理器。在创建或审查React组件时使用。 以下正文为该技能的原始 SKILL.md 内容(英文),上方安装命令可直接使用。
name: react-patterns description: React component patterns including functional components, hooks, state management, API integration, loading/error states, and event handlers. Use when creating or reviewing React components.
React Patterns
Overview
These patterns ensure consistent, maintainable React components with TypeScript. Follow these guidelines for all frontend development.
Component Structure
Functional Components Only
Always use functional components with hooks:
export function TaskList({ tasks, onTaskClick }: TaskListProps) {
return (
<ul className="task-list">
{tasks.map(task => (
<TaskItem key={task.id} task={task} onClick={onTaskClick} />
))}
</ul>
);
}
Component File Structure
components/
├── TaskList/
│ ├── TaskList.tsx # Component implementation
│ ├── TaskList.css # Component styles
│ └── index.ts # Re-export
TypeScript Interfaces
Props Interfaces
Define props interfaces for every component:
interface TaskListProps {
tasks: Task[];
onTaskClick: (task: Task) => void;
isLoading?: boolean;
}
export function TaskList({ tasks, onTaskClick, isLoading = false }: TaskListProps) {
// ...
}
State Management
useState for Local State
const [title, setTitle] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
useEffect for Side Effects
useEffect(() => {
fetchTasks();
}, []);
Loading and Error States
Always Handle All States
if (isLoading) {
return <div className="loading">Loading tasks...</div>;
}
if (error) {
return <div className="error">Error: {error}</div>;
}
if (tasks.length === 0) {
return <div className="empty">No tasks yet. Create one!</div>;
}
Event Handlers
Naming Convention
Prefix with handle for component handlers, on for props:
interface TaskItemProps {
task: Task;
onComplete: (id: string) => void; // Prop callback
}
function TaskItem({ task, onComplete }: TaskItemProps) {
function handleCompleteClick() { // Local handler
onComplete(task.id);
}
// ...
}
CSS Styling
Component-Scoped CSS
Each component has its own CSS file with BEM-like naming:
.task-list- Block.task-item- Element.task-item.completed- Modifier