Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)280k · #237

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.md

Sao 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

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

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/useCallback only 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 import a Server Component from a Client Component file — compose them via children instead

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-boundary for 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

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự