Logo React Patterns

React Patterns

Tổ chức
cosmicstack-labs
react-patterns

Component patterns, hooks, state management, and performance optimization for React applications

Tổng quan

Nhà phát hànhcosmicstack-labs
Kho mãmercury-agent-skills
Tên kỹ năngreact-patterns
Sao
485
Bản fork
63
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được cosmicstack-labs công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI React Patterns trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/frontend/react-patterns
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/cosmicstack-labs/mercury-agent-skills.git /tmp/mercury-agent-skills
mkdir -p .claude/skills
cp -r /tmp/mercury-agent-skills/categories/frontend/react-patterns .claude/skills/react-patterns
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật React Patterns trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải React Patterns ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên React Patterns không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

React Patterns

Build React applications that are composable, performant, and maintainable.

Core Principles

1. Composition Over Configuration

Build small, focused components and compose them. Avoid giant components with many configuration props. Children and slots are your friends.

2. State Management Is About Proximity

Keep state as close to where it's used as possible. Lift state up only when truly shared. Context is not a state management solution.

3. Derive, Don't Duplicate

Derived state (computed from existing state) should never be stored separately. Use useMemo for expensive derivations, compute inline for cheap ones.

4. Effects Are Escape Hatches

useEffect is for synchronizing with external systems (API, DOM, subscriptions). Don't use it for derived state or event handlers.


React Patterns Maturity Model

LevelComponentsStateEffectsPerformance
1: BasicClass components, mix of concernsLocal state onlyRaw useEffectsNot considered
2: FoundationalFunctional components, some hooksLifting state, some contextCleanup in effectsReact.memo basics
3: ProficientCompound components, custom hooksuseReducer, Zustand/ContextCustom hooks encapsulate effectsuseMemo, useCallback
4: AdvancedRender props, slots, polymorphicServer state (TanStack Query)Controlled side effectsCode splitting, virtualization
5: ExpertHeadless UI, state machinesZustand + server state + URLxState or custom event busConcurrent features, streaming SSR

Target: Level 3+ for production apps. Level 4 for complex applications.


Actionable Guidance

Component Patterns

1. Compound Components
tsx
// Expose related components that share implicit state
<Select value={selected} onChange={setSelected}>
  <Select.Option value="1">Option 1</Select.Option>
  <Select.Option value="2">Option 2</Select.Option>
  <Select.Option value="3">Option 3</Select.Option>
</Select>

When to use: Complex UI widgets (selects, tabs, accordions, menus) where children share state.

Implementation:

tsx
const SelectContext = createContext<SelectContextType | null>(null);

function Select({ children, value, onChange }: SelectProps) {
  return (
    <SelectContext.Provider value={{ value, onChange }}>
      <select className="select">{children}</select>
    </SelectContext.Provider>
  );
}

Select.Option = function Option({ value, children }: OptionProps) {
  const ctx = useContext(SelectContext);
  if (!ctx) throw new Error('Option must be inside Select');
  return (
    <option
      value={value}
      selected={ctx.value === value}
      onClick={() => ctx.onChange(value)}
    >
      {children}
    </option>
  );
};
2. Custom Hooks

Extract complex logic into reusable hooks. Hooks are your primary code reuse mechanism.

tsx
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

// Usage
function SearchResults({ query }: { query: string }) {
  const debouncedQuery = useDebounce(query, 300);
  const { data } = useQuery(['search', debouncedQuery], fetchResults);
  // ...
}
3. Render Props / Slots

Let consumers control rendering while you control behavior.

tsx
function DataList<T>({
  items,
  renderItem,
  renderEmpty,
}: {
  items: T[];
  renderItem: (item: T, index: number) => ReactNode;
  renderEmpty?: () => ReactNode;
}) {
  if (items.length === 0) {
    return renderEmpty?.() ?? <p>No items found.</p>;
  }
  return <ul>{items.map((item, i) => <li key={i}>{renderItem(item, i)}</li>)}</ul>;
}

State Management

Local State (useState)

Best for: UI state, form inputs, toggle flags, single-component data.

tsx
const [isOpen, setIsOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
Complex State (useReducer)

Best for: State with multiple sub-values, complex update logic, dependent state transitions.

tsx
type State = { count: number; step: number };
type Action = { type: 'increment' } | { type: 'decrement' } | { type: 'setStep'; step: number };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment': return { ...state, count: state.count + state.step };
    case 'decrement': return { ...state, count: state.count - state.step };
    case 'setStep':   return { ...state, step: action.step };
  }
}
Server State (TanStack Query / SWR)

Best for: API data, caching, refetching, optimistic updates.

tsx
function UserProfile({ userId }: { userId: string }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
  });

  if (isLoading) return <Skeleton />;
  if (error) return <ErrorMessage error={error} />;
  return <UserCard user={data} />;
}
Shared Client State (Zustand / Jotai)

Best for: Global UI state (theme, sidebar, auth), cross-component state.

tsx
import { create } from 'zustand';

const useStore = create((set) => ({
  theme: 'light',
  sidebar: 'open',
  toggleTheme: () => set((state) => ({
    theme: state.theme === 'light' ? 'dark' : 'light'
  })),
}));

Performance Optimization

1. Memoization Rules
ToolUse WhenDon't Use When
React.memoComponent renders often with same propsProps change every render anyway
useMemoExpensive calculations (>1ms)Simple arithmetic or access patterns
useCallbackPassing stable callbacks to memo'd childrenPassing to DOM elements
tsx
// Good: useMemo for expensive computation
const sortedItems = useMemo(
  () => items.sort((a, b) => expensiveCompare(a, b)),
  [items]
);

// Overkill: useMemo for trivial computation
const total = useMemo(() => items.length + 1, [items]); // Just compute inline

// Good: useCallback for stable function reference
const handleClick = useCallback(() => {
  setCount(c => c + 1);
}, []); // No dependencies — stable forever
2. Code Splitting
tsx
import { lazy, Suspense } from 'react';

const AdminPanel = lazy(() => import('./AdminPanel'));

function App() {
  return (
    <Suspense fallback={<LoadingSkeleton />}>
      {isAdmin ? <AdminPanel /> : <UserPanel />}
    </Suspense>
  );
}
3. Virtualization

For long lists (1000+ items), use react-window or @tanstack/virtual:

tsx
import { useVirtualizer } from '@tanstack/react-virtual';

function VirtualList({ items }: { items: Item[] }) {
  const parentRef = useRef(null);
  const virtualizer = useVirtualizer({
    count: items.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 50,
  });

  return (
    <div ref={parentRef} style={{ height: '400px', overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize() }}>
        {virtualizer.getVirtualItems().map((virtualItem) => (
          <div key={virtualItem.key} style={{
            position: 'absolute',
            top: 0,
            transform: `translateY(${virtualItem.start}px)`,
          }}>
            {items[virtualItem.index].name}
          </div>
        ))}
      </div>
    </div>
  );
}

Common Anti-Patterns

Anti-PatternProblemFix
Big useEffectSingle effect doing multiple, unrelated thingsSplit into multiple effects
State as derived dataStoring computed values in stateUse useMemo or compute inline
Prop drillingPassing props through 5+ layersUse composition or context (sparingly)
Context for everythingRe-rendering entire tree on any state changeSplit contexts, use Zustand/Jotai
Inline functions in renderBreaking React.memo optimizationMove to stable references with useCallback
Over-optimizationMemoizing everything prematurelyProfile first, optimize second

Common Mistakes

  1. Overusing context: Context causes re-renders in all consumers. For high-frequency updates, use Zustand or Jotai.
  2. Missing dependency arrays: The React linting rule is not optional. Include all refs and state used inside effects.
  3. Async in effects without cleanup: Fetch requests need AbortController. SetTimeouts need clearing.
  4. State cascades: Setting state in one effect that triggers another effect. Prefer derived state.
  5. Not using key props: Key props on lists enable efficient reconciliation. Use stable IDs, not indices.
  6. Direct DOM manipulation: You're using React. Let React manage the DOM. Use refs sparingly.

Câu hỏi thường gặp

Kỹ năng AI React Patterns làm được gì?

Component patterns, hooks, state management, and performance optimization for React applications

Vì sao nên dùng React Patterns trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. React Patterns là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài React Patterns trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/frontend/react-patterns. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng React Patterns?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng React Patterns với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng React Patterns với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI React Patterns có miễn phí không?

Có. Kỹ năng này được cosmicstack-labs phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇