react-component

Use when creating UI components in React - functional components, hooks, custom hooks, or component composition patterns. NOT when backend logic, API routes, or non-React frameworks are involved. Triggers: "create component", "build widget", "KPI card", "form", "modal", "custom hook", "useContext", "useState", "useEffect".

242 stars

Best use case

react-component is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. Use when creating UI components in React - functional components, hooks, custom hooks, or component composition patterns. NOT when backend logic, API routes, or non-React frameworks are involved. Triggers: "create component", "build widget", "KPI card", "form", "modal", "custom hook", "useContext", "useState", "useEffect".

Use when creating UI components in React - functional components, hooks, custom hooks, or component composition patterns. NOT when backend logic, API routes, or non-React frameworks are involved. Triggers: "create component", "build widget", "KPI card", "form", "modal", "custom hook", "useContext", "useState", "useEffect".

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "react-component" skill to help with this workflow task. Context: Use when creating UI components in React - functional components, hooks, custom hooks, or component composition patterns.
NOT when backend logic, API routes, or non-React frameworks are involved.
Triggers: "create component", "build widget", "KPI card", "form", "modal", "custom hook", "useContext", "useState", "useEffect".

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/react-component/SKILL.md --create-dirs "https://raw.githubusercontent.com/aiskillstore/marketplace/main/skills/awais68/react-component/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/react-component/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How react-component Compares

Feature / Agentreact-componentStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Use when creating UI components in React - functional components, hooks, custom hooks, or component composition patterns. NOT when backend logic, API routes, or non-React frameworks are involved. Triggers: "create component", "build widget", "KPI card", "form", "modal", "custom hook", "useContext", "useState", "useEffect".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# React Component Skill

## Overview

Expert guidance for building React functional components, hooks, and composition patterns. Focuses on TypeScript, performance, accessibility, and modern React best practices.

## When This Skill Applies

This skill triggers when users request:
- **UI Components**: "Create a student KPI card", "Build a modal", "Form component"
- **Hooks**: "Custom attendance hook", "useContext for theme", "useState for data"
- **Patterns**: "Component composition", "HOC", "render props"
- **ERP Widgets**: KPI cards, forms, data tables, dashboards

## Core Rules

### 1. Functional Components Always

```typescript
// ✅ GOOD: Functional component with TypeScript
interface StudentKPICardProps {
  studentName: string;
  attendance: number;
  loading?: boolean;
}

export const StudentKPICard = React.memo(({ studentName, attendance, loading = false }: StudentKPICardProps) => {
  const [isHovered, setIsHovered] = useState(false);

  if (loading) return <LoadingSkeleton />;

  return <div>{/* content */}</div>;
});
```

**Requirements:**
- Always use functional components (no class components)
- Type all props interfaces explicitly
- Use `React.memo` for components receiving same props frequently
- Use `React.forwardRef` when ref forwarding is needed

### 2. Hooks Usage

```typescript
// ✅ GOOD: Proper hook usage with cleanup
export const AttendanceMonitor = ({ studentId }: { studentId: string }) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;
    const fetchAttendance = async () => {
      try {
        const result = await api.getAttendance(studentId);
        if (isMounted) setData(result);
      } catch (err) {
        if (isMounted) setError(err.message);
      }
    };
    fetchAttendance();

    return () => {
      isMounted = false;
    };
  }, [studentId]);

  return /* JSX */;
};
```

**Requirements:**
- `useState`: For local component state only
- `useEffect`: For side-effects with proper cleanup functions
- `useContext`: For global state (theme, auth, language)
- Always include all dependencies in dependency array
- Use `useCallback`/`useMemo` for expensive operations in lists

### 3. Custom Hooks

```typescript
// ✅ GOOD: Custom hook with proper types
interface UseAttendanceResult {
  data: AttendanceData | null;
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

export const useAttendance = (studentId: string): UseAttendanceResult => {
  const [data, setData] = useState<AttendanceData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchAttendance = useCallback(async () => {
    setLoading(true);
    try {
      const result = await api.getAttendance(studentId);
      setData(result);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [studentId]);

  useEffect(() => {
    fetchAttendance();
  }, [fetchAttendance]);

  return { data, loading, error, refetch: fetchAttendance };
};
```

**Requirements:**
- All custom hooks must start with `use` prefix
- Extract reusable logic into hooks
- Return typed interfaces for hook results
- Include loading, error states, and retry mechanisms
- Keep hooks focused on single responsibility

### 4. Component Composition

```typescript
// ✅ GOOD: Composition via children prop
interface CardProps {
  title: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
}

export const Card = ({ title, children, footer }: CardProps) => (
  <div className="card">
    <h2>{title}</h2>
    <div className="card-content">{children}</div>
    {footer && <div className="card-footer">{footer}</div>}
  </div>
);

// Usage
<Card title="Student Info" footer={<Button>Save</Button>}>
  <StudentDetails />
</Card>

// ✅ GOOD: Higher-order component pattern
export const withLoading = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
  return (props: P & { loading?: boolean }) => {
    const { loading = false, ...rest } = props;
    if (loading) return <LoadingSpinner />;
    return <WrappedComponent {...(rest as P)} />;
  };
};
```

**Requirements:**
- Prefer composition over inheritance
- Use `children` prop for flexible content
- Use render props when component needs to share data
- Use HOCs sparingly and with proper TypeScript types
- Keep components small and focused (single responsibility)

## Output Requirements

### Code Files

1. **Component file** (`ComponentName.tsx`):
   - Functional component with typed props
   - Hooks applied correctly
   - Exported as named export
   - Default export when appropriate

2. **Test file** (`ComponentName.test.tsx`):
   - Jest/Vitest + React Testing Library
   - Test component renders with props
   - Test user interactions
   - Test loading/error states
   - Accessibility tests

3. **Storybook file** (`ComponentName.stories.tsx`):
   - Default story
   - Variant stories (loading, error, different states)
   - Props table for documentation

### Integration Requirements

- **shadcn/ui**: Use existing shadcn components when available
- **Accessibility**: Follow WCAG 2.1 AA guidelines (use @ui-ux-designer for a11y audit)
- **Styling**: Tailwind CSS with design system tokens
- **i18n**: Prepare components for internationalization (no hardcoded text)

### Documentation

- **PHR**: Create Prompt History Record for each component development
- **ADR**: Document hook pattern decisions for complex custom hooks
- **Comments**: Add comments only for non-obvious logic

## Workflow

1. **Understand Requirements**
   - Clarify component purpose, props, and interactions
   - Identify state needs (local vs global)
   - Determine reusability potential

2. **Design Props Interface**
   - Define TypeScript interface for all props
   - Mark optional props with `?`
   - Use discriminated unions for variant types

3. **Implement Component**
   - Write functional component
   - Apply hooks with proper dependencies
   - Handle loading/error states
   - Ensure accessibility (ARIA attributes)

4. **Test Component**
   - Write unit tests for all code paths
   - Test user interactions
   - Verify accessibility

5. **Create Stories**
   - Document component with Storybook
   - Show all variants and states
   - Add controls for interactive exploration

## Quality Checklist

Before completing any component:

- [ ] **React 19+ Hooks Rules**: No dependency issues, proper cleanup in useEffect
- [ ] **TypeScript Props**: Exhaustive type definitions, no `any` types
- [ ] **Custom Hooks**: All prefixed with 'use', single responsibility
- [ ] **Composition**: Used over inheritance, flexible via children/render props
- [ ] **Performance**: `useCallback`/`useMemo` for expensive operations in lists
- [ ] **Accessibility**: Proper ARIA labels, keyboard navigation support
- [ ] **Error Handling**: Graceful error states, no console errors
- [ ] **Loading States**: Clear loading indicators for async operations
- [ ] **Tests**: Unit tests cover all branches and interactions
- [ ] **Stories**: Storybook stories document component usage

## Common Patterns

### Data Fetching Component

```typescript
export const StudentList = () => {
  const { data: students, loading, error } = useStudents();

  if (loading) return <LoadingSkeleton count={5} />;
  if (error) return <ErrorState message={error} />;

  return (
    <ul>
      {students?.map((student) => (
        <StudentItem key={student.id} student={student} />
      ))}
    </ul>
  );
};
```

### Form Component with Validation

```typescript
interface FormValues {
  name: string;
  email: string;
}

export const StudentForm = () => {
  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>();

  const onSubmit = async (data: FormValues) => {
    await api.createStudent(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Input {...register('name', { required: true })} error={errors.name} />
      <Input {...register('email', { required: true })} error={errors.email} />
      <Button type="submit">Save</Button>
    </form>
  );
};
```

## References

- React Documentation: https://react.dev
- TypeScript React Cheatsheet: https://react-typescript-cheatsheet.netlify.app
- React Testing Library: https://testing-library.com/docs/react-testing-library/intro
- shadcn/ui: https://ui.shadcn.com

Related Skills

web-component-design

242
from aiskillstore/marketplace

Master React, Vue, and Svelte component patterns including CSS-in-JS, composition strategies, and reusable component architecture. Use when building UI component libraries, designing component APIs, or implementing frontend design systems.

react-native-design

242
from aiskillstore/marketplace

Master React Native styling, navigation, and Reanimated animations for cross-platform mobile development. Use when building React Native apps, implementing navigation patterns, or creating performant animations.

next-cache-components

242
from aiskillstore/marketplace

Next.js 16 Cache Components - PPR, use cache directive, cacheLife, cacheTag, updateTag

ui-component-patterns

242
from aiskillstore/marketplace

Build reusable, maintainable UI components following modern design patterns. Use when creating component libraries, implementing design systems, or building scalable frontend architectures. Handles React patterns, composition, prop design, TypeScript, and component best practices.

react-useeffect

242
from aiskillstore/marketplace

React useEffect best practices from official docs. Use when writing/reviewing useEffect, useState for derived values, data fetching, or state synchronization. Teaches when NOT to use Effect and better alternatives.

react-dev

242
from aiskillstore/marketplace

This skill should be used when building React components with TypeScript, typing hooks, handling events, or when React TypeScript, React 19, Server Components are mentioned. Covers type-safe patterns for React 18-19 including generic components, proper event typing, and routing integration (TanStack Router, React Router).

react-state-management

242
from aiskillstore/marketplace

Master modern React state management with Redux Toolkit, Zustand, Jotai, and React Query. Use when setting up global state, managing server state, or choosing between state management solutions.

react-native-architecture

242
from aiskillstore/marketplace

Build production React Native apps with Expo, navigation, native modules, offline sync, and cross-platform patterns. Use when developing mobile apps, implementing native integrations, or architecting React Native projects.

react-modernization

242
from aiskillstore/marketplace

Upgrade React applications to latest versions, migrate from class components to hooks, and adopt concurrent features. Use when modernizing React codebases, migrating to React Hooks, or upgrading to latest React versions.

react-flow-node-ts

242
from aiskillstore/marketplace

Create React Flow node components with TypeScript types, handles, and Zustand integration. Use when building custom nodes for React Flow canvas, creating visual workflow editors, or implementing node-based UI components.

react-flow-architect

242
from aiskillstore/marketplace

Expert ReactFlow architect for building interactive graph applications with hierarchical node-edge systems, performance optimization, and auto-layout integration. Use when Claude needs to create or optimize ReactFlow applications for: (1) Interactive process graphs with expand/collapse navigation, (2) Hierarchical tree structures with drag & drop, (3) Performance-optimized large datasets with incremental rendering, (4) Auto-layout integration with Dagre, (5) Complex state management for nodes and edges, or any advanced ReactFlow visualization requirements.

hig-components-system

242
from aiskillstore/marketplace

Apple HIG guidance for system experience components: widgets, live activities, notifications, complications, home screen quick actions, top shelf, watch faces, app clips, and app shortcuts. Use when asked about: "widget design", "live activity", "notification design", "complication", "home screen quick action", "top shelf", "watch face", "app clip", "app shortcut", "system experience". Also use when the user says "how do I design a widget," "what should my notification look like," "how do Live Activities work," "should I make an App Clip," or asks about surfaces outside the main app. Cross-references: hig-components-status for progress in widgets, hig-inputs for interaction patterns, hig-technologies for Siri and system integration.