react-patterns
Fungsinya
Tool ini membantu Anda menulis kode untuk React, library populer untuk membangun antarmuka pengguna. Tool ini menyediakan praktik terbaik dan pola (pattern) agar kode Anda lebih teratur, lebih cepat, dan mudah diakses.
Kapan dipakai
- ✓Saat membuat komponen React baru.
- ✓Saat meninjau atau memperbaiki kode React yang sudah ada.
- ✓Saat memutuskan cara mengelola data dan state dalam aplikasi Anda.
Link skill
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.mdSalin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.
Cara pakai
Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.
Pesan siap tempel
Untuk Claude Code, Codex, atau Cursor: jalankan di folder proyek, lalu skill langsung terpasang.
Unduh SKILL.md lalu taruh di folder skill agen Anda.
Contoh permintaan ke AI
“Bagaimana cara mengelola state form di React secara efisien?”
5 skill baru setiap minggu. 1 menit baca.
Cara kerjanya
Tool ini menganalisis kode React Anda dan menyarankan pola yang direkomendasikan untuk mengatur komponen, mengelola data, dan menangani side effect. Tool ini didasarkan pada prinsip seperti menjaga kode tetap bersih dan berfokus pada komposisi.
Konten teknis (SKILL.md asli)
Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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));
…
Pertanyaan umum
Apa itu 'Server Components' dan 'Client Components'?
Ini adalah dua cara mengatur kode React. Server component hanya berjalan di server, sedangkan client component berjalan di browser pengguna. Cara ini membantu mengoptimalkan performa.
Bagaimana cara menangani error di React?
Tool ini menyarankan penggunaan 'Error Boundaries' untuk menangkap error yang terjadi saat komponen dirender, sehingga Anda bisa menampilkan pesan error yang ramah alih-alih aplikasi berhenti total.
Kapan sebaiknya menggunakan `useState`, `Context`, atau library eksternal untuk mengelola state?
Tool ini menawarkan panduan untuk memutuskan: `useState` untuk satu komponen, `Context` untuk data yang dibagikan ke bagian komponen yang jauh di dalam pohon komponen, dan library eksternal untuk pembaruan yang sering dan dibagikan.
Detail
Deskripsi asli dari pembuat
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
Popularitas
- Bintang GitHub
- 280k
- Peringkat
- #237
- Lisensi
- MIT
- Diperbarui
- 15/10/2026
Komentar
- …
Skill lain dari repositori ini
accessibility
280kMembantu agent Anda membuat antarmuka yang ramah untuk semua orang. Memastikan website dan aplikasi tetap bisa dipakai penyandang disabilitas, seperti tunanetra.
agent-architecture-audit
280kMembuat agent Anda memeriksa apakah semuanya berjalan dengan benar. Agent akan menemukan dan memperbaiki masalah pada sistem AI agar bekerja sesuai harapan.
agent-eval
280kMembantu agent Anda membandingkan berbagai alat coding AI. Mengukur mana yang lebih cepat, lebih murah, dan lebih andal untuk tugas tertentu.
agent-harness-construction
280kMembuat agent Anda lebih memahami cara menyelesaikan tugas. Agent mengoptimalkan alat dan instruksi yang digunakan agar peluang berhasilnya lebih besar.
Skill serupa
dream-loop
260kMemungkinkan agent Anda mendorong scene 3D atau aplikasi visual menuju kualitas grafis tinggi dengan membandingkan screenshot dengan concept art secara berulang.
pretext
260kMembangun demo browser yang main-main di mana teks mengalir mengelilingi bentuk yang bergerak, membentuk level game, atau pecah menjadi partikel.
page-agent
260kMembantu agent Anda menambahkan asisten AI bawaan ke aplikasi web, sehingga pengguna dapat memberi perintah dalam bahasa sehari-hari yang kemudian dijalankan oleh halaman.