| name | react-component-pattern |
| description | null |
Component Pattern
Category: react · Status: 🟢 Active
When to use
Khi tạo mới hoặc refactor một React function component.
Steps
- Xác định component là presentational hay container; tách logic phức tạp ra custom hook.
- Định nghĩa Props interface rõ ràng, ưu tiên required, không dùng
any.
- Destructure props ở signature, đặt default value tại đây.
- Giữ render thuần: side-effect đưa vào
useEffect/handler.
- Early-return cho loading/error/empty trước khi render chính.
- Named export, 1 component/file.
Template
interface UserCardProps {
user: User;
onSelect?: (id: string) => void;
}
export function UserCard({ user, onSelect }: UserCardProps) {
if (!user) return null;
return <button type="button" onClick={() => onSelect?.(user.id)}>{user.name}</button>;
}
Example
Good: Props có type, handler optional gọi qua ?., early-return khi thiếu data.
Avoid: export default function(props: any), fetch trong render.
Checklist