react-best-practices

v2026.09.24

Use when the user needs React-specific patterns — hooks, component composition, Server Components, error boundaries, rendering optimization, and testing strategies. Triggers: hooks design, component composition, Server vs Client component decision, error boundary placement, context optimization, rendering performance.

GitHub
安装命令
npx skhub add pixel-process-ug/react-best-practices
Markdown
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.

发现
标签

此技能尚未发布标签。

版本
最新版本元数据

版本

v2026.09.24

发布时间

Sep 24, 2026

分类

未分类

许可证

MIT

源路径

templates/skills/react-best-practices

默认分支

main

最新提交

cc7fcb7

Tree SHA

7a49a40