agentleFS
benshapyrobenshapyro/cadre-devkit-claude/skills/react-patterns/SKILL.md

react-patterns

Skill9 starsChanged 12 months agoMITView on GitHub

Modern React patterns for TypeScript applications including hooks, state management, and component composition. Use when building React components, managing state, or implementing React best practices.

  • Sends data out

29 other projects use a version of this, 1 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use typescript-strict, fastapi-patterns and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • kevinaimonsterSkill

    typescript-strict

    TypeScript strict mode and advanced type system assistant. Helps write strictly-typed TypeScript code with generics, type guards, utility types, conditional types, mapped types, and template literal types. Trigger when user says 'TypeScript types' 'type gymnastics' 'TypeScript generics' 'strict TypeScript' 'type guard' 'TS类型' 'TypeScript严格模式' '类型体操' '泛型怎么写' 'TS type help'. Keywords: TypeScript, strict mode, generics, type guard, utility types, conditional types, mapped types, template literal types, infer, extends, keyof, typeof, type narrowing, discriminated unions, type assertion, type predicate, type gymnastics, TS, 类型体操, 泛型, 类型守卫, 严格类型

    Also in 3 projects that use this

  • hieutrtrSkill

    fastapi-patterns

    FastAPI framework mechanics and advanced patterns. Use when configuring middleware, creating dependency injection chains, implementing WebSocket endpoints, customizing OpenAPI documentation, setting up CORS, building authentication dependencies (JWT validation, role-based access), implementing background tasks, or managing application lifespan (startup/shutdown). Does NOT cover basic endpoint CRUD or repository/service patterns (use python-backend-expert) or testing (use pytest-patterns).

    Also in 3 projects that use this

  • xfstudioSkill

    python-patterns

    Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.

    Also in 5 projects that use this

  • LangChainSkill

    docker-patterns

    Best practices for Docker containerization and multi-stage builds

    Also in 4 projects that use this

  • AnthropicSkill

    testing-strategy

    Design test strategies and test plans. Trigger with "how should we test", "test strategy for", "write tests for", "test plan", "what tests do we need", or when the user needs help with testing approaches, coverage, or test architecture.

    Also in 4 projects that use this

  • rohitg00Skill

    django-patterns

    Django architecture patterns including DRF, ORM optimization, signals, middleware, and project structure

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

8 rules. 0 are common, 6 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 25 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use React.memo() for pure components receiving complex props

    line 287
  2. Very specific:

    Use useMemo for expensive derived state

    line 289
  3. Distinctive:

    Don't mutate state directly

    line 335
  4. Distinctive:

    Don't call hooks conditionally or in loops

    line 336
  5. Distinctive:

    Don't use array index as key for dynamic lists

    line 337
  6. Distinctive:

    Don't fetch data in useEffect without cleanup/cancellation

    line 338
  7. Distinctive:

    Don't ignore dependency array warnings

    line 339
  8. Distinctive:

    Don't overuse context for frequently-changing values

    line 340

“Common” is measured: kept by at least 6 in 10 of the 25 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

React Patterns Skill

Modern React patterns for TypeScript applications.

Component Structure

File Organization

components/
├── ui/                    # Reusable primitives (Button, Input, Card)
├── features/              # Feature-specific components
│   └── auth/
│       ├── LoginForm.tsx
│       └── SignupForm.tsx
├── layouts/               # Page layouts
└── providers/             # Context providers

Component Template

interface ComponentNameProps {
  // Required props first
  title: string;
  onAction: () => void;
  // Optional props with defaults
  variant?: 'primary' | 'secondary';
  disabled?: boolean;
  children?: React.ReactNode;
}

export function ComponentName({
  title,
  onAction,
  variant = 'primary',
  disabled = false,
  children,
}: ComponentNameProps) {
  return (/* JSX */);
}

Hooks Best Practices

useState

// Prefer explicit types for complex state
const [user, setUser] = useState<User | null>(null);

// Use functional updates when depending on previous state
setCount(prev => prev + 1);

// Group related state or use useReducer for complex state
const [form, setForm] = useState({ name: '', email: '' });

useEffect

// Always specify dependencies explicitly
useEffect(() => {
  fetchData();
}, [userId]); // Only re-run when userId changes

// Cleanup subscriptions
useEffect(() => {
  const subscription = subscribe();
  return () => subscription.unsubscribe();
}, []);

// Avoid objects/arrays in deps - extract primitives
const { id } = user;
useEffect(() => { /* ... */ }, [id]); // Not [user]

useMemo / useCallback

// Memoize expensive calculations
const sortedItems = useMemo(
  () => items.sort((a, b) => a.name.localeCompare(b.name)),
  [items]
);

// Memoize callbacks passed to children
const handleClick = useCallback(() => {
  onAction(id);
}, [onAction, id]);

Custom Hooks

// Extract reusable logic into custom hooks
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;
}

// Prefix with "use", return typed values
function useAuth() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  // ... logic

  return { user, loading, signIn, signOut } as const;
}

State Management

Context + useReducer (Complex Local State)

// Define action types and state
type State = { count: number; loading: boolean };
type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'setLoading'; payload: boolean };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment': return { ...state, count: state.count + 1 };
    case 'decrement': return { ...state, count: state.count - 1 };
    case 'setLoading': return { ...state, loading: action.payload };
  }
}

// Context provider
const CounterContext = createContext<{
  state: State;
  dispatch: React.Dispatch<Action>;
} | null>(null);

function CounterProvider({ children }: { children: React.ReactNode }) {
  const [state, dispatch] = useReducer(reducer, { count: 0, loading: false });
  return (
    <CounterContext.Provider value={{ state, dispatch }}>
      {children}
    </CounterContext.Provider>
  );
}

// Custom hook for consuming
function useCounter() {
  const context = useContext(CounterContext);
  if (!context) throw new Error('useCounter must be used within CounterProvider');
  return context;
}

Server State (React Query / TanStack Query)

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// Fetching data
function useUsers() {
  return useQuery({
    queryKey: ['users'],
    queryFn: () => fetch('/api/users').then(res => res.json()),
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

// Mutations with optimistic updates
function useUpdateUser() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (user: User) =>
      fetch(`/api/users/${user.id}`, {
        method: 'PUT',
        body: JSON.stringify(user),
      }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
  });
}

// Usage
function UserList() {
  const { data: users, isLoading, error } = useUsers();
  const updateUser = useUpdateUser();

  if (isLoading) return <Spinner />;
  if (error) return <Error message={error.message} />;

  return (/* render users */);
}

When to Use What

ScenarioSolution
Simple component stateuseState
Complex state with many actionsuseReducer
State shared across componentsContext + useReducer
Server data (fetch, cache, sync)React Query / SWR
Global app state (auth, theme)Context or Zustand

Component Patterns

Composition over Props

// Prefer composition
<Card>
  <Card.Header>Title</Card.Header>
  <Card.Body>Content</Card.Body>
</Card>

// Over prop drilling
<Card header="Title" body="Content" />

Render Props / Children as Function

interface DataFetcherProps<T> {
  url: string;
  children: (data: T, loading: boolean) => React.ReactNode;
}

function DataFetcher<T>({ url, children }: DataFetcherProps<T>) {
  const { data, loading } = useFetch<T>(url);
  return <>{children(data, loading)}</>;
}

Controlled vs Uncontrolled

// Controlled - parent owns state
<Input value={value} onChange={setValue} />

// Uncontrolled - component owns state, use ref to access
<Input defaultValue="initial" ref={inputRef} />

Error Handling

Error Boundaries

class ErrorBoundary extends Component<Props, State> {
  state = { hasError: false, error: null };

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('Error caught:', error, info);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? <div>Something went wrong</div>;
    }
    return this.props.children;
  }
}

Async Error Handling

const [error, setError] = useState<Error | null>(null);

async function handleSubmit() {
  try {
    setError(null);
    await submitForm(data);
  } catch (e) {
    setError(e instanceof Error ? e : new Error('Unknown error'));
  }
}

Performance

Avoid Unnecessary Renders

  • Use React.memo() for pure components receiving complex props
  • Split context providers to minimize re-renders
  • Use useMemo for expensive derived state
  • Lazy load heavy components with React.lazy()

Code Splitting

const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <HeavyComponent />
    </Suspense>
  );
}

TypeScript Integration

Event Handlers

function handleChange(e: React.ChangeEvent<HTMLInputElement>) { }
function handleSubmit(e: React.FormEvent<HTMLFormElement>) { }
function handleClick(e: React.MouseEvent<HTMLButtonElement>) { }

Generic Components

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
  keyExtractor: (item: T) => string;
}

function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
  return (
    <ul>
      {items.map(item => (
        <li key={keyExtractor(item)}>{renderItem(item)}</li>
      ))}
    </ul>
  );
}

Anti-Patterns

  • Don't mutate state directly
  • Don't call hooks conditionally or in loops
  • Don't use array index as key for dynamic lists
  • Don't fetch data in useEffect without cleanup/cancellation
  • Don't ignore dependency array warnings
  • Don't overuse context for frequently-changing values

Version

  • v1.0.0 (2025-12-05): Added YAML frontmatter, initial documented version

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.