mcpField
R
react

react

github.com/claude-dev-suiteDevelopment4643 installsUpdated 4d ago
Repository

About react

react is a reference skill for developers building React applications. It covers core component and hook patterns, performance, accessibility, security, testing, and troubleshooting.

Key features

  1. 01Functional component and props patterns
  2. 02Essential React hooks
  3. 03State and composition guidance
  4. 04Performance optimization
  5. 05Accessibility and security practices
  6. 06Testing and troubleshooting guidance

Use cases

  1. 01Structuring reusable React components
  2. 02Managing local and shared state
  3. 03Diagnosing hook and rendering issues
  4. 04Checking accessibility and production readiness

MCP support

The README points to mcp__documentation__fetch_docs with technology `react` for comprehensive React documentation.

Install

Copy the command and run it in a terminal.

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

After installing, type/reactin Claude Code to confirm it loaded.

Bundled filesquick-ref/component-patterns.mdquick-ref/hooks-cheatsheet.md

Details

From the project README

React Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: react for comprehensive documentation on hooks, components, and React patterns.

Component Patterns

Functional Components (Preferred)
function UserCard({ name, email }: UserCardProps) {
  return (
    <div className="card">
      <h2>{name}</h2>
      <p>{email}</p>
    </div>
  );
}
Props Typing
interface Props {
  title: string;
  count?: number;
  children: React.ReactNode;
  onClick: (id: string) => void;
}

Essential Hooks

HookPurpose
useStateLocal state
useEffectSide effects, subscriptions
useContextAccess context values
useRefDOM refs, mutable values
useMemoMemoize expensive computations
useCallbackMemoize functions
useReducerComplex state logic

Key Patterns

  • Composition over inheritance
  • Lift state up for shared state
  • Props drilling → use Context or state library
  • Controlled vs Uncontrolled inputs

Performance

  • Use React.memo() for expensive pure components
  • Memoize with useMemo/useCallback only when needed
  • Use key prop correctly in lists
  • Lazy load with React.lazy() + Suspense

Production Readiness

Security Best Practices
// NEVER use dangerouslySetInnerHTML with user input
// BAD
<div dangerouslySetInnerHTML={{ __html: userInput }} />

// GOOD - Sanitize with DOMPurify
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />

// Avoid exposing sensitive data in client-side state
// BAD
const [apiKey, setApiKey] = useState(process.env.API_KEY);

// GOOD - API keys should stay server-side
// Use API routes or server actions instead

// Validate all external URLs
const isValidUrl = (url: string) => {
  try {
    const parsed = new URL(url);
    return ['http:', 'https:'].includes(parsed.protocol);
  } catch {
    return false;
  }
};
Error Boundaries
import { ErrorBoundary } from 'react-error-boundary';

function ErrorFallback({ error, resetErrorBoundary }: FallbackProps) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre>{error.message}</pre>
      <button onClick={resetErrorBoundary}>Try again</button>
    </div>
  );
}

// Usage
<ErrorBoundary
  FallbackComponent={ErrorFallback}
  onReset={() => window.location.reload()}
  onError={(error, info) => {
    // Log to error reporting service
    logErrorToService(error, info);
  }}
>
  <App />
</ErrorBoundary>
Performance Optimization
// Code splitting with lazy loading
const Dashboard = lazy(() => import('./Dashboard'));

function App() {
  return (
    <Suspense fallback={<Skeleton />}>
      <Dashboard />
    </Suspense>
  );
}

// Memoization - use sparingly, only for expensive components
const ExpensiveList = memo(function ExpensiveList({ items }: Props) {
  return items.map(item => <ExpensiveItem key={item.id} {...item} />);
});

// Virtualization for large lists
import { FixedSizeList } from 'react-window';

function VirtualList({ items }: { items: Item[] }) {
  return (
    <FixedSizeList
      height={400}
      itemCount={items.length}
      itemSize={50}
      width="100%"
    >
      {({ index, style }) => (
        <div style={style}>{items[index].name}</div>
      )}
    </FixedSizeList>
  );
}
Accessibility (a11y)
// Use semantic HTML
<button onClick={handleClick}>Submit</button>  // NOT <div onClick>

// ARIA labels for icons/images
<button aria-label="Close dialog" onClick={onClose}>
  <XIcon />
</button>

// Focus management
const dialogRef = useRef<HTMLDivElement>(null);
useEffect(() => {
  dialogRef.current?.focus();
}, [isOpen]);

// Keyboard navigation
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape') onClose();
  if (e.key === 'Tab') trapFocus(e);
};
Testing Setup
// Component testing with Testing Library
import { render, screen, userEvent } from '@testing-library/react';

test('submits form with user data', async () => {
  const onSubmit = vi.fn();
  render(<Form onSubmit={onSubmit} />);

  await userEvent.type(screen.getByLabelText(/email/i), '[email protected]');
  await userEvent.click(screen.getByRole('button', { name: /submit/i }));

  expect(onSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});
Monitoring Metrics
MetricAlert Threshold
Largest Contentful Paint (LCP)> 2.5s
First Input Delay (FID)> 100ms
Cumulative Layout Shift (CLS)> 0.1
JavaScript bundle size> 200KB (gzipped)
Component render time> 16ms
Build & Bundle Optimization
// vite.config.ts
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown'],
        },
      },
    },
    sourcemap: true,  // For error tracking in production
  },
});
Checklist
  • Error boundaries wrapping critical sections
  • No sensitive data in client state
  • DOMPurify for any HTML rendering
  • Lazy loading for route-based code splitting
  • Virtualization for large lists (>100 items)
  • Semantic HTML and ARIA labels
  • Keyboard navigation support
  • Core Web Vitals monitored
  • Bundle size optimized (<200KB gzip)
  • Source maps for production debugging
  • Error reporting service integrated

When NOT to Use This Skill

  • React 19 specific features (Actions, useActionState, use()) - Use react-19 skill instead
  • Advanced performance optimization - Use react-performance skill instead
  • Form handling patterns - Use react-forms or react-hook-form skills instead
  • Routing - Use react-router skill instead
  • Testing - Use react-testing skill instead
  • Component design patterns - Use react-patterns skill instead

Anti-Patterns

Anti-PatternProblemSolution
Mutating state directlyDoesn't trigger re-renderUse setState with new object/array
Missing dependency arraysStale closures, memory leaksInclude all dependencies or use ESLint
useEffect for derived stateExtra re-rendersCalculate during render or use useMemo
Props drilling deeplyHard to maintainUse Context or state library
Inline object/array in JSXBreaks memoizationExtract to constant or useMemo
New functions in renderChild re-renders unnecessarilyUse useCallback
Forgetting cleanup in useEffectMemory leaksReturn cleanup function
Using index as keyIncorrect re-rendersUse stable unique ID

Quick Troubleshooting

IssueLikely CauseFix
Component not re-renderingState mutationUse setState with new reference
Infinite loop in useEffectMissing/wrong dependenciesAdd deps or use functional update
"Cannot read property of undefined"Async data not loadedAdd null checks or loading state
Memory leak warningMissing cleanupReturn cleanup function from useEffect
Children not updatingUsing index as keyUse unique stable ID
Handler not firingEvent propagation stoppedCheck stopPropagation() calls
Stale state in callbackClosure over old stateUse functional setState

Reference Documentation

Comments

Markdown supported