react-patterns
Skill này làm gì
Công cụ này giúp bạn viết code cho React, một thư viện phổ biến để xây dựng giao diện người dùng. Nó cung cấp các thực hành tốt nhất và mẫu để code có tổ chức, nhanh hơn và dễ tiếp cận hơn.
Khi nào nên dùng
- ✓Khi tạo các thành phần React mới.
- ✓Khi xem lại hoặc cải thiện code React hiện có.
- ✓Khi quyết định cách quản lý dữ liệu và trạng thái trong ứng dụng.
Liên kết skill
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm sao để quản lý trạng thái biểu mẫu trong React một cách hiệu quả?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Công cụ phân tích code React của bạn và đề xuất các mẫu được khuyến nghị để tổ chức thành phần, quản lý dữ liệu và xử lý side effect. Nó dựa trên các nguyên tắc như giữ code gọn gàng và tập trung vào việc ghép các thành phần lại với nhau.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
React Patterns
Idiomatic React 18/19 patterns for building robust, accessible, performant component trees.
When to Activate
- Writing or modifying React function components, custom hooks, or component trees
- Reviewing JSX/TSX files
- Designing state shape or component composition
- Migrating class components or older
forwardRef/useEffect-heavy code - Choosing between local state, lifted state, context, and external stores
- Working with Server Components / Client Components (Next.js App Router, RSC)
- Implementing forms with React 19 actions or controlled inputs
- Wiring data fetching with TanStack Query / SWR / RSC
Core Principles
1. Render is a Pure Function of Props and State
// Good: derive during render
function Cart({ items }: { items: CartItem[] }) {
const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
return <span>{formatMoney(total)}</span>;
}
// Bad: derived state stored separately
function Cart({ items }: { items: CartItem[] }) {
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(items.reduce((sum, i) => sum + i.price * i.qty, 0));
}, [items]);
return <span>{formatMoney(total)}</span>;
}
Derived state in useEffect adds a render cycle, can desync, and obscures the data flow.
2. Side Effects Outside Render
Effects, mutations, network calls, and subscriptions live in event handlers or useEffect — never in the render body.
3. Composition Over Inheritance
React has no inheritance model for components. Compose with children, render props, or component props.
Hooks Discipline
See rules/react/hooks.md for the full ruleset. Highlights:
- Top-level only, never conditional
- Cleanup every subscription, interval, listener
- Functional updater (
setX(prev => prev + 1)) when new state depends on old - Default position: do not memoize — add
useMemo/useCallbackonly when a profiler or a dependency chain proves it matters - Extract a custom hook only when the same hook sequence appears in 2+ components
State Location Decision Tree
Used by one component?
-> useState inside it
Used by parent + a few descendants?
-> lift to nearest common ancestor
Used across distant branches AND low-frequency reads (theme, auth, locale)?
-> React Context
High-frequency updates shared across the tree?
-> external store (Zustand, Jotai, Redux Toolkit)
Derived from a server?
-> server-state library (TanStack Query, SWR, RSC fetch)
Most pages do not need context or a global store. Resist abstraction until duplicated lifting becomes painful.
Server / Client Components (RSC)
// Server Component - default, async, never ships JS for itself
export default async function ProductPage({ params }: { params: { id: string } }) {
const product = await db.product.findUnique({ where: { id: params.id } });
if (!product) notFound();
return <ProductView product={product} />;
}
// Client Component - opt in with "use client"
"use client";
export function AddToCartButton({ productId }: { productId: string }) {
const [pending, startTransition] = useTransition();
return (
<button
disabled={pending}
onClick={() => startTransition(() => addToCart(productId))}
>
{pending ? "Adding..." : "Add to cart"}
</button>
);
}
Boundaries:
- Server -> Client: pass serializable props or
children - Client -> Server: invoke Server Actions via
<form action={...}>or imperatively from event handlers - Never
importa Server Component from a Client Component file — compose them viachildreninstead
Suspense + Error Boundaries
<ErrorBoundary fallback={<ErrorView />}>
<Suspense fallback={<UserSkeleton />}>
<UserDetail id={id} />
</Suspense>
</ErrorBoundary>
- Place Suspense boundaries close to the data, not at the route root — progressively reveal content
- Error Boundary remains a class API; use
react-error-boundaryfor a hook-friendly wrapper - A boundary catches errors thrown during render, lifecycle, and constructors of its children — NOT in event handlers or async code
Forms
React 19 form actions (preferred for new code)
"use client";
import { useActionState } from "react";
const initial = { error: null as string | null };
async function updateUserAction(_prev: typeof initial, formData: FormData) {
"use server";
const parsed = UserSchema.safeParse(Object.fromEntries(formData));
…
Câu hỏi thường gặp
'Server Component' và 'Client Component' là gì?
Đây là hai cách tổ chức code React. Server component chỉ chạy trên máy chủ, còn client component chạy trong trình duyệt của người dùng. Cách này giúp tối ưu hiệu năng.
Làm sao để xử lý lỗi trong React?
Công cụ gợi ý dùng 'Error Boundary' để bắt các lỗi xảy ra khi render thành phần, cho phép hiển thị thông báo lỗi thân thiện thay vì làm ứng dụng bị sập.
Khi nào nên dùng `useState`, `Context` hoặc thư viện bên ngoài để quản lý trạng thái?
Công cụ đưa ra hướng dẫn: `useState` cho một thành phần, `Context` cho dữ liệu dùng chung ở các phần xa trong cây thành phần, và thư viện bên ngoài cho các cập nhật thường xuyên được chia sẻ.
Chi tiết
Mô tả gốc của tác giả
React 18/19 patterns including hooks discipline, server/client component boundaries, Suspense + error boundaries, form actions, data fetching, state management decision trees, and accessibility-first composition. Use when writing or reviewing React components.
repo: affaan-m/ECC
Độ phổ biến
- Sao GitHub
- 280k
- Vị trí xếp hạng
- #237
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
accessibility
280kGiúp agent của bạn tạo giao diện mà ai cũng dùng được, đảm bảo website và app hoạt động tốt với người khuyết tật như người mù hoặc khó vận động.
agent-architecture-audit
280kGiúp agent của bạn kiểm tra xem mọi thứ có hoạt động đúng không, đồng thời tìm và sửa các lỗi trong hệ thống AI để chúng chạy như mong đợi.
agent-eval
280kGiúp agent của bạn so sánh các công cụ lập trình AI khác nhau, đo xem công cụ nào nhanh hơn, rẻ hơn và đáng tin cậy hơn cho từng tác vụ.
agent-harness-construction
280kGiúp agent của bạn hiểu rõ hơn cách thực hiện tác vụ, tối ưu các công cụ và chỉ dẫn mà agent dùng để tăng khả năng thành công.
Skill tương tự
dream-loop
260kGiúp agent của bạn đẩy một cảnh 3D hoặc ứng dụng trực quan lên chất lượng đồ họa cao, bằng cách so ảnh chụp màn hình với concept art và lặp lại.
pretext
260kXây dựng các bản demo trình duyệt vui nhộn, trong đó chữ tự chảy quanh các hình chuyển động, tạo màn chơi hoặc tách thành các hạt.
page-agent
260kGiúp agent của bạn thêm một trợ lý AI tích hợp vào ứng dụng web, để người dùng ra lệnh bằng ngôn ngữ thường và trang thực hiện theo.