Token导航 LogoToken导航TokenDH.com
前端设计external-servicegithub未标认证来源可访问许可证需确认审计通过

react-contextReact context 前端

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

665

周安装

28

GitHub Stars

12

下载量

233
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:react-context(React context 前端)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/react-context
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill react-context
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill react-context

简介

管理 React 全局状态与跨组件通信。

  • 提供 Context 创建与 Provider 配置指导。
  • 适用于主题、用户信息等共享数据。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。
  • 避免滥用导致不必要的重渲染。react-context 属于前端设计类 Skill,可作为该场景下的辅助能力补充。
  • 复杂状态建议拆分多个 Context。

SKILL.md

React Context

Full Reference: See advanced.md for context selectors with useSyncExternalStore, dependency injection, React 19 use(), testing context, and TypeScript patterns.
Deep Knowledge: Use mcp__documentation__fetch_docs with technology: react topic: context for comprehensive documentation.

Basic Usage

import { createContext, useContext, ReactNode } from 'react';

// 1. Create context with default value
interface ThemeContextValue {
  theme: 'light' | 'dark';
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextValue | null>(null);

// 2. Create Provider component
function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');

  const toggleTheme = useCallback(() => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  }, []);

  const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

// 3. Create custom hook for consuming
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
}

// 4. Use in components
function Header() {
  const { theme, toggleTheme } = useTheme();

  return (
    <header className={theme}>
      <button onClick={toggleTheme}>
        Switch to {theme === 'light' ? 'dark' : 'light'}
      </button>
    </header>
  );
}

// 5. Wrap app with provider
function App() {
  return (
    <ThemeProvider>
      <Header />
      <Main />
    </ThemeProvider>
  );
}

Context with Reducer

For complex state management:

interface AuthState {
  user: User | null;
  isLoading: boolean;
  error: string | null;
}

type AuthAction =
  | { type: 'LOGIN_START' }
  | { type: 'LOGIN_SUCCESS'; payload: User }
  | { type: 'LOGIN_ERROR'; payload: string }
  | { type: 'LOGOUT' };

const initialState: AuthState = {
  user: null,
  isLoading: false,
  error: null,
};

function authReducer(state: AuthState, action: AuthAction): AuthState {
  switch (action.type) {
    case 'LOGIN_START':
      return { ...state, isLoading: true, error: null };
    case 'LOGIN_SUCCESS':
      return { ...state, isLoading: false, user: action.payload };
    case 'LOGIN_ERROR':
      return { ...state, isLoading: false, error: action.payload };
    case 'LOGOUT':
      return initialState;
    default:
      return state;
  }
}

// Separate state and dispatch contexts for optimization
const AuthStateContext = createContext<AuthState | null>(null);
const AuthDispatchContext = createContext<React.Dispatch<AuthAction> | null>(null);

function AuthProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(authReducer, initialState);

  return (
    <AuthStateContext.Provider value={state}>
      <AuthDispatchContext.Provider value={dispatch}>
        {children}
      </AuthDispatchContext.Provider>
    </AuthStateContext.Provider>
  );
}

// Custom hooks
function useAuthState() {
  const context = useContext(AuthStateContext);
  if (!context) {
    throw new Error('useAuthState must be used within AuthProvider');
  }
  return context;
}

function useAuthDispatch() {
  const context = useContext(AuthDispatchContext);
  if (!context) {
    throw new Error('useAuthDispatch must be used within AuthProvider');
  }
  return context;
}

Performance Optimization

Split State and Actions

// Problem: All consumers re-render when any value changes
const BadContext = createContext({ count: 0, increment: () => {} });

// Solution: Separate frequently changing values
const CountContext = createContext(0);
const CountActionsContext = createContext({ increment: () => {} });

function CountProvider({ children }: { children: ReactNode }) {
  const [count, setCount] = useState(0);

  // Memoize actions object
  const actions = useMemo(() => ({
    increment: () => setCount(c => c + 1),
    decrement: () => setCount(c => c - 1),
    reset: () => setCount(0),
  }), []);

  return (
    <CountContext.Provider value={count}>
      <CountActionsContext.Provider value={actions}>
        {children}
      </CountActionsContext.Provider>
    </CountContext.Provider>
  );
}

// Now components can subscribe to only what they need
function DisplayCount() {
  const count = useContext(CountContext);
  console.log('DisplayCount rendered'); // Only when count changes
  return <span>{count}</span>;
}

function IncrementButton() {
  const { increment } = useContext(CountActionsContext);
  console.log('IncrementButton rendered'); // Never re-renders!
  return <button onClick={increment}>+</button>;
}

Context Composition

Combine multiple contexts cleanly:

// Compose multiple providers
function AppProviders({ children }: { children: ReactNode }) {
  return (
    <ThemeProvider>
      <AuthProvider>
        <SettingsProvider>
          <NotificationsProvider>
            {children}
          </NotificationsProvider>
        </SettingsProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

// Or use a composition helper
type ProviderProps = { children: ReactNode };
type Provider = React.ComponentType<ProviderProps>;

function composeProviders(...providers: Provider[]) {
  return function ComposedProvider({ children }: ProviderProps) {
    return providers.reduceRight(
      (child, Provider) => <Provider>{child}</Provider>,
      children
    );
  };
}

const AppProviders = composeProviders(
  ThemeProvider,
  AuthProvider,
  SettingsProvider,
  NotificationsProvider
);

// Usage
function App() {
  return (
    <AppProviders>
      <Router />
    </AppProviders>
  );
}

Context vs Other State Solutions

SolutionUse Case
ContextDependency injection, theme, auth, rarely changing data
useStateLocal component state
useReducerComplex local state logic
Zustand/JotaiFrequent updates, performance critical
TanStack QueryServer state, caching
ReduxLarge apps, time-travel debugging

When NOT to Use Context

// ❌ Frequently changing data (causes unnecessary re-renders)
const PositionContext = createContext({ x: 0, y: 0 });

// ✅ Use a proper state library instead
const useMouseStore = create((set) => ({
  position: { x: 0, y: 0 },
  setPosition: (pos) => set({ position: pos }),
}));

// ❌ Complex nested updates
const FormContext = createContext({
  values: {},
  errors: {},
  touched: {},
  // ...many more fields
});

// ✅ Use a form library
const { register, handleSubmit } = useForm();

Common Pitfalls

IssueCauseSolution
Unnecessary re-rendersContext value not memoizedUse useMemo for value
"Cannot read undefined"Missing ProviderAdd null check or throw in hook
Stale closuresMissing dependenciesAdd to dependency array
Performance issuesLarge frequently updating contextSplit into multiple contexts

Best Practices

  • Always create custom hooks for consuming context
  • Memoize context value with useMemo
  • Split state and dispatch into separate contexts
  • Use TypeScript for type safety
  • Throw error if context used outside provider
  • Don't use context for frequently changing values
  • Don't pass entire state when only part is needed
  • Don't deeply nest too many providers

When NOT to Use This Skill

  • React 19 use() hook - Use react-19 skill for conditional context reading
  • State management libraries - Use Zustand, Redux, or Jotai skills for complex state
  • Server state - Use TanStack Query skill for data fetching and caching
  • Form state - Use React Hook Form skill for form-specific state

Anti-Patterns

Anti-PatternProblemSolution
Context for frequently changing valuesPerformance issues, many re-rendersUse state library (Zustand) or useSyncExternalStore
Not memoizing context valueNew object every render, all consumers re-renderUse useMemo for context value
Single context with all stateUnnecessary re-rendersSplit into multiple focused contexts
Not throwing in custom hookPoor error messagesThrow error if context is null/undefined
Deeply nested providersHard to read, maintainUse provider composition helper
Context for local component stateUnnecessary complexityUse useState in component
Default value that's never usedMisleadingUse null/undefined and throw in hook

Quick Troubleshooting

IssueLikely CauseFix
"Cannot read property of undefined"Missing ProviderWrap component tree with Provider
All consumers re-renderingContext value not memoizedWrap value in useMemo
Context value undefinedUsed outside ProviderCheck Provider wraps component
Poor performanceLarge frequently-changing contextSplit context or use state library
Type errorsWrong context typeCheck TypeScript generic in createContext
Stale valuesMissing dependenciesAdd values to useMemo dependencies
Nested providers confusingToo many providersUse composition helper function

Reference Documentation

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.08%
按下载量换算79

Claude

29.36%
按下载量换算68

Cursor

19.35%
按下载量换算45

Gemini CLI

9.98%
按下载量换算23

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills