Перейти к содержанию
Skillpedia
Сайты и интерфейсы (фронтенд)280k · #237

react-patterns

Что он делает

Этот инструмент помогает писать код для React, популярной библиотеки для создания пользовательских интерфейсов. Он предоставляет лучшие практики и паттерны, которые делают код более организованным, быстрым и доступным.

Когда использовать

  • ✓При создании новых компонентов React.
  • ✓При проверке или улучшении существующего кода React.
  • ✓При выборе способа управления данными и состоянием в приложении.

Ссылка на скилл

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-patterns/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Как эффективно управлять состоянием форм в 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/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));

…
Частые вопросы

Что такое «Server Components» и «Client Components»?

Это два способа организации кода в 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
Обновлён
15.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы