React Patterns logo

React Patterns

Organization
cosmicstack-labs
react-patterns

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

Overview

Publishercosmicstack-labs
Repositorymercury-agent-skills
Skill namereact-patterns
Stars
485
Forks
63
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by cosmicstack-labs on GitHub. Read the source before you install it.

Installation

Install the React Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/frontend/react-patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

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
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable React Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads React Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so React Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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.

Frequently asked questions

What does the React Patterns AI skill do?

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

Why use React Patterns on TypingMind?

Because you install it once and use it with any model. React Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install React Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/cosmicstack-labs/mercury-agent-skills/tree/main/categories/frontend/react-patterns. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use React Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with React Patterns?

As many as you like. As long as a model supports skills, you can use React Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the React Patterns AI skill free?

Yes. It is published on GitHub by cosmicstack-labs under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇