react-patterns
하는 일
이 도구는 사용자 인터페이스를 만드는 인기 라이브러리인 React로 코드를 작성하도록 돕습니다. 코드를 더 체계적이고, 빠르고, 접근하기 쉽게 만드는 모범 사례와 패턴을 제공합니다.
사용하는 경우
- ✓새 React 컴포넌트를 만들 때.
- ✓기존 React 코드를 검토하거나 개선할 때.
- ✓애플리케이션에서 데이터와 상태를 어떻게 관리할지 정할 때.
스킬 링크
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“React에서 폼 상태를 효율적으로 관리하려면 어떻게 해야 할까요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
이 도구는 React 코드를 분석하고, 컴포넌트 구성, 데이터 관리, 부수 효과 처리에 권장되는 패턴을 제안합니다. 코드를 깔끔하게 유지하고 구성(composition)에 집중하는 원칙에 기반합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
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));
…
자주 묻는 질문
‘서버 컴포넌트’와 ‘클라이언트 컴포넌트’란 무엇인가요?
React 코드를 구성하는 두 가지 방식입니다. 서버 컴포넌트는 서버에서만 실행되고, 클라이언트 컴포넌트는 사용자의 브라우저에서 실행됩니다. 성능을 최적화하는 데 도움이 됩니다.
React에서 오류는 어떻게 처리하나요?
도구는 ‘에러 바운더리(Error Boundaries)’를 사용해 컴포넌트 렌더링 중 발생하는 오류를 잡으라고 제안합니다. 그러면 애플리케이션이 멈추는 대신 친절한 오류 메시지를 보여 줄 수 있습니다.
상태 관리에는 useState, Context, 외부 라이브러리 중 무엇을 써야 하나요?
도구는 판단 기준을 제공합니다. 하나의 컴포넌트에는 useState, 컴포넌트 트리의 먼 부분이 공유하는 데이터에는 Context, 자주 바뀌는 공유 상태에는 외부 라이브러리를 사용하라고 안내합니다.
상세 정보
작성자의 원본 설명
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
인기도
- GitHub 스타
- 280k
- 순위
- #237
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.