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のコードを分析し、コンポーネントの整理、データ管理、副作用の扱い方について推奨パターンを提案します。コードを簡潔に保つことや、合成(コンポジション)を重視するといった原則に基づいています。
技術的な内容(元の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));
…
よくある質問
「Server Components」と「Client Components」とは何ですか?
Reactコードを整理する2つの方法です。Server Componentsはサーバー上でのみ実行され、Client Componentsはユーザーのブラウザ上で実行されます。これにより、パフォーマンスの最適化に役立ちます。
Reactでエラーを処理するにはどうすればよいですか?
「Error Boundary(エラーバウンダリ)」を使い、コンポーネントの描画中に発生したエラーを捕捉することを提案します。これにより、アプリケーションがクラッシュする代わりに、分かりやすいエラーメッセージを表示できます。
状態管理には、useState、Context、外部ライブラリのどれを使うべきですか?
判断の目安として、1つのコンポーネントだけで使う場合は`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エージェントが誰にとっても使いやすいインターフェースを作れるように手助けします。目が見えない方や身体の動きに制限のある方など、障害のある人にとってもWebサイトやアプリが正しく動くようにします。
agent-architecture-audit
280kエージェントがすべて正しく動いているかを確認できるようにします。AIシステムの問題を見つけて修正し、期待どおりに動くようにします。
agent-eval
280kエージェントが異なるAIコーディングツールを比較できるようにします。特定のタスクにおいて、どれがより速く、安く、信頼性が高いかを測定します。
agent-harness-construction
280kエージェントがタスクの進め方をよりよく理解できるようにします。エージェントが使うツールや指示を最適化し、成功する可能性を高めます。
似ているスキル
dream-loop
260kコンセプトアートと比べながら、ライブのスクリーンショットを繰り返し確認して、3Dのシーンやビジュアルアプリを高いグラフィック品質に近づけるようエージェントを支援します。
pretext
260kテキストが動く図形の周りに回り込んだり、ゲームのレベルを形作ったり、粒子になって崩れたりする、遊び心のあるブラウザのデモを作るようエージェントを支援します。
page-agent
260kウェブアプリに組み込みのAIアシスタントを加え、利用者が平易な言葉で命令し、ページがそれを実行できるようにするのを、エージェントが支援します。