Token导航 LogoToken导航TokenDH.com
开发规范操作浏览器github未标认证来源可访问许可证需确认审计通过

react-best-practicesReact 最佳实践

Agent Skill

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

总安装

727

周安装

30

GitHub Stars

1

下载量

238
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/pixel-process-ug/superkit-agents --skill react-best-practices

简介

react-best-practices 用于辅助前端页面、组件、样式和交互逻辑的开发与维护,适合生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码。

  • 适用于前端开发中的最佳实践指导,可整理组件结构或定位布局和性能问题。
  • 使用时需结合项目现有设计系统、路由和构建方式,避免生成孤立片段。
  • 涉及页面改动时应配合本地预览和构建检查确认视觉效果。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

React Best Practices

Overview

Apply modern React patterns to build maintainable, performant, and testable applications. This skill covers React 18/19 features including Server Components, hooks best practices, component composition, error boundaries, Suspense, context optimization, and rendering performance. It complements the senior-frontend skill with React-specific depth.

Announce at start: "I'm using the react-best-practices skill for React-specific patterns."


Phase 1: Analyze Component Requirements

Goal: Understand the component's responsibility and data requirements before coding.

Actions

  1. Identify the component's single responsibility
  2. Determine data requirements (server vs client data)
  3. Choose Server Component (default) or Client Component
  4. Identify state management needs
  5. Plan error and loading states

Server vs Client Decision Table

NeedComponent TypeReason
Direct data fetching (DB, API)Server (default)No client JS, faster
Event handlers (onClick, onChange)Client ('use client')Needs browser interactivity
useState / useReducerClientState requires client runtime
useEffect / useLayoutEffectClientSide effects require client
Browser APIs (window, localStorage)ClientServer has no browser
Third-party libs using client featuresClientLibrary requires client
No interactivity neededServer (default)Smaller bundle, faster

STOP — Do NOT proceed to Phase 2 until:

  • Component responsibility is defined (single purpose)
  • Server vs Client decision is made with rationale
  • Data requirements are mapped

Phase 2: Implement with Appropriate Patterns

Goal: Apply the correct React patterns for the component's needs.

Actions

  1. Apply appropriate composition pattern
  2. Implement hooks correctly
  3. Add error boundaries and Suspense
  4. Optimize rendering where profiling shows need
  5. Write tests that verify behavior

STOP — Do NOT proceed to Phase 3 until:

  • Patterns match the component's actual needs
  • No unnecessary complexity (no premature optimization)
  • Tests cover user-visible behavior

Phase 3: Test and Verify

Goal: Verify component behavior through tests.

Actions

  1. Write tests using accessible queries
  2. Test user interactions and outcomes
  3. Test error and loading states
  4. Verify accessibility

Query Priority (React Testing Library)

PriorityQueryUse For
1stgetByRoleAny element with ARIA role
2ndgetByLabelTextForm fields
3rdgetByPlaceholderTextFields without labels
4thgetByTextNon-interactive elements
LastgetByTestIdWhen nothing else works

STOP — Testing complete when:

  • User interactions produce expected outcomes
  • Error states are tested
  • Accessibility checks pass

Hooks Best Practices

useState

// Functional updates for state based on previous state
setCount(prev => prev + 1);

// Lazy initialization for expensive initial values
const [data, setData] = useState(() => computeExpensiveInitialValue());

// Group related state
const [form, setForm] = useState({ name: '', email: '', role: 'user' });

useEffect

Dependency Array Rules

  • Include ALL values from component scope that change over time
  • Functions inside effect should be defined inside effect or wrapped in useCallback
  • Never lie about dependencies (ESLint: react-hooks/exhaustive-deps)

Cleanup Pattern

useEffect(() => {
  const controller = new AbortController();
  async function fetchData() {
    try {
      const res = await fetch(url, { signal: controller.signal });
      const data = await res.json();
      setData(data);
    } catch (e) {
      if (e.name !== 'AbortError') setError(e);
    }
  }
  fetchData();
  return () => controller.abort();
}, [url]);

When NOT to Use useEffect

Instead of useEffect for...Use This
Data fetchingReact Query, SWR, or Server Components
Transforming dataCompute during render
User eventsEvent handlers
Syncing external storesuseSyncExternalStore

Custom Hooks Rules

  • Name starts with use
  • Encapsulate reusable stateful logic
  • One hook per concern
  • Return object (not array) for > 2 values
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;
}

Component Composition Patterns

Compound Components

function Tabs({ children, defaultValue }: TabsProps) {
  const [activeTab, setActiveTab] = useState(defaultValue);
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div role="tablist">{children}</div>
    </TabsContext.Provider>
  );
}

Tabs.Tab = function Tab({ value, children }: TabProps) {
  const { activeTab, setActiveTab } = useTabsContext();
  return (
    <button role="tab" aria-selected={activeTab === value} onClick={() => setActiveTab(value)}>
      {children}
    </button>
  );
};

Tabs.Panel = function Panel({ value, children }: PanelProps) {
  const { activeTab } = useTabsContext();
  if (activeTab !== value) return null;
  return <div role="tabpanel">{children}</div>;
};

Composition Decision Table

PatternUse WhenExample
Compound ComponentsRelated components sharing implicit stateTabs, Accordion, Menu
Slots (Children)Complex content layoutCard with Header/Body/Footer
Render PropsChild needs parent data for flexible renderingDataFetcher with custom render
Higher-Order ComponentCross-cutting concerns (legacy)withAuth, withTheme
Custom HookReusable stateful logic without UIuseDebounce, useLocalStorage

Slots Pattern

// Prefer composition over props for complex content
// Bad
<Card title="Hello" subtitle="World" icon={<Star />} actions={<Button>Edit</Button>} />

// Good
<Card>
  <Card.Header>
    <Card.Icon><Star /></Card.Icon>
    <Card.Title>Hello</Card.Title>
  </Card.Header>
  <Card.Actions>
    <Button>Edit</Button>
  </Card.Actions>
</Card>

Error Boundaries

Placement Strategy Decision Table

LevelPurposeExample
Route levelCatch page-level crasheserror.tsx in Next.js
Feature levelIsolate feature failuresWrap each major section
Data levelWrap async data componentsAround Suspense boundaries
Never leaf levelToo granular, adds noiseDo not wrap individual buttons

Suspense

// Nested Suspense for granular loading
<Suspense fallback={<PageSkeleton />}>
  <Header />
  <Suspense fallback={<SidebarSkeleton />}>
    <Sidebar />
  </Suspense>
  <Suspense fallback={<ContentSkeleton />}>
    <MainContent />
  </Suspense>
</Suspense>

Context Optimization

Problem: Context causes unnecessary re-renders

Solution Decision Table

TechniqueUse WhenExample
Split contexts by frequencySome values update often, some rarelyThemeContext (rare) vs UIStateContext (frequent)
Memoize context valueProvider re-renders with same datauseMemo(() => ({state, dispatch}), [state])
Use selectors (Zustand/Jotai)Need fine-grained subscriptionsuseStore(state => state.user.name)
Lift state upOnly parent needs to re-renderPass data as props to memoized children

Rendering Optimization

Memoization Decision Table

TechniqueUse WhenDo NOT Use When
React.memoRenders often with same props AND re-render is expensiveProps change every render
useMemoExpensive computation OR referential equality for depsSimple calculations
useCallbackStable function ref for memoized childrenFunction not passed as prop
None (default)Always start herePremature optimization

Rule: Profile BEFORE memoizing. Premature memoization is the most common React anti-pattern.

Virtualization

For lists > 100 items:

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

Server Component Rules

  • Cannot use hooks
  • Cannot use browser APIs
  • Cannot pass functions as props to Client Components
  • CAN import and render Client Components
  • CAN pass serializable data to Client Components
// Server Component — fetches data directly
async function UserProfile({ userId }: { userId: string }) {
  const user = await db.user.findUnique({ where: { id: userId } });
  return (
    <div>
      <h1>{user.name}</h1>
      <UserActions userId={userId} /> {/* Client Component child */}
    </div>
  );
}

// Client Component — handles interactivity
'use client';
function UserActions({ userId }: { userId: string }) {
  const [isFollowing, setIsFollowing] = useState(false);
  return <Button onClick={() => toggleFollow(userId)}>Follow</Button>;
}

Anti-Patterns / Common Mistakes

Anti-PatternWhy It Is WrongCorrect Approach
useEffect for data fetchingRace conditions, no cache, no dedupReact Query or Server Components
Prop drilling > 2 levelsTight coupling, maintenance painComposition, context, or Zustand
Storing derived stateState that can be computed is unnecessary stateCompute during render
useEffect to sync state from propsUnnecessary effect, stale closuresDerive during render or use key prop
Monolithic components (> 200 lines)Hard to read, test, maintainExtract sub-components
Index as key for dynamic listsIncorrect reconciliation, stale stateStable unique ID
Direct DOM manipulationBypasses React reconciliationUse refs sparingly, prefer state
Testing state values directlyImplementation detail, breaks on refactorTest user-visible outcomes
Memoizing everythingAdds complexity, often slowerProfile first, optimize second

Documentation Lookup (Context7)

Use mcp__context7__resolve-library-id then mcp__context7__query-docs for up-to-date docs. Returned docs override memorized knowledge.

  • react — for hooks, context, suspense, server components, or React 19+ changes
  • next.js — for App Router patterns, data fetching, or server actions

Integration Points

SkillRelationship
senior-frontendFrontend skill uses React patterns from this skill
testing-strategyReact testing follows the strategy pyramid
clean-codeComponent code follows clean code principles
performance-optimizationReact rendering optimization follows measurement methodology
webapp-testingE2E tests validate React component behavior
code-reviewReview checks for React anti-patterns
acceptance-testingUI acceptance criteria drive component tests

Skill Type

FLEXIBLE — Apply these patterns based on the specific React version, project structure, and team conventions. The principles are consistent, but implementation details may vary. Always profile before optimizing.

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

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

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

平台分布

Codex

35%
按下载量换算83

Claude

30.12%
按下载量换算72

Cursor

18.42%
按下载量换算44

Gemini CLI

9.37%
按下载量换算22

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

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

来源信息

继续浏览同类 Skills