본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)280k · #237

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

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/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));

…
자주 묻는 질문

‘서버 컴포넌트’와 ‘클라이언트 컴포넌트’란 무엇인가요?

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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬