react
This skill is loaded by `frontend-developer` when:
What this skill does
# React Framework - Quick Reference
**Version**: 1.0.0
**Framework**: React 18+
**Use Case**: Fast lookups during active development
---
## When to Use
This skill is loaded by `frontend-developer` when:
- `package.json` contains `"react"` dependency (โฅ18.0.0)
- Project has `.jsx` or `.tsx` files in `src/`
- User explicitly mentions "React" in task description
- Next.js, Vite, or Create React App detected
**Minimum Detection Confidence**: 0.8 (80%)
---
## Quick Start
### Basic Component
```tsx
import { FC } from 'react';
interface Props {
title: string;
onAction?: () => void;
}
export const MyComponent: FC<Props> = ({ title, onAction }) => {
return (
<div>
<h1>{title}</h1>
<button onClick={onAction}>Action</button>
</div>
);
};
```
---
## Core Patterns
### 1. Component Design
#### Functional Component Structure
```tsx
// 1. Imports (grouped and sorted)
import { useState, useEffect } from 'react';
import type { FC, ReactNode } from 'react';
// 2. Types/Interfaces
interface Props {
children: ReactNode;
className?: string;
}
// 3. Component
export const Component: FC<Props> = ({ children, className }) => {
// 4. Hooks (state, effects, context)
const [state, setState] = useState<string>('');
useEffect(() => {
// Side effects
}, []);
// 5. Event handlers
const handleClick = () => {
setState('clicked');
};
// 6. Early returns (error states, loading)
if (!children) return null;
// 7. Main render
return <div className={className}>{children}</div>;
};
```
#### Component Composition
```tsx
// Container/Presentational Pattern
interface User {
id: number;
name: string;
}
// Container: Logic and data fetching
export const UserProfileContainer: FC<{ userId: number }> = ({ userId }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(setUser)
.finally(() => setLoading(false));
}, [userId]);
if (loading) return <LoadingSpinner />;
if (!user) return <ErrorMessage />;
return <UserProfile user={user} />;
};
// Presentational: Pure UI
interface UserProfileProps {
user: User;
}
export const UserProfile: FC<UserProfileProps> = ({ user }) => {
return (
<div>
<h2>{user.name}</h2>
</div>
);
};
```
#### Compound Components
```tsx
interface TabsProps {
children: ReactNode;
defaultTab?: string;
}
interface TabsContextType {
activeTab: string;
setActiveTab: (tab: string) => void;
}
const TabsContext = createContext<TabsContextType | undefined>(undefined);
export const Tabs: FC<TabsProps> & {
List: FC<{ children: ReactNode }>;
Tab: FC<{ id: string; children: ReactNode }>;
Panel: FC<{ id: string; children: ReactNode }>;
} = ({ children, defaultTab = '' }) => {
const [activeTab, setActiveTab] = useState(defaultTab);
return (
<TabsContext.Provider value={{ activeTab, setActiveTab }}>
<div className="tabs">{children}</div>
</TabsContext.Provider>
);
};
Tabs.List = ({ children }) => <div className="tabs-list">{children}</div>;
Tabs.Tab = ({ id, children }) => {
const context = useContext(TabsContext);
return (
<button
className={context?.activeTab === id ? 'active' : ''}
onClick={() => context?.setActiveTab(id)}
>
{children}
</button>
);
};
Tabs.Panel = ({ id, children }) => {
const context = useContext(TabsContext);
return context?.activeTab === id ? <div>{children}</div> : null;
};
// Usage:
<Tabs defaultTab="tab1">
<Tabs.List>
<Tabs.Tab id="tab1">Tab 1</Tabs.Tab>
<Tabs.Tab id="tab2">Tab 2</Tabs.Tab>
</Tabs.List>
<Tabs.Panel id="tab1">Content 1</Tabs.Panel>
<Tabs.Panel id="tab2">Content 2</Tabs.Panel>
</Tabs>
```
---
### 2. Hooks
#### useState - Local State
```tsx
// Basic usage
const [count, setCount] = useState(0);
const [user, setUser] = useState<User | null>(null);
// Functional updates (when new state depends on old)
setCount(prevCount => prevCount + 1);
// Lazy initialization (expensive computation)
const [data, setData] = useState(() => {
return expensiveComputation();
});
```
#### useEffect - Side Effects
```tsx
// Run once on mount
useEffect(() => {
fetchData();
}, []); // Empty dependency array
// Run when dependencies change
useEffect(() => {
fetchUser(userId);
}, [userId]);
// Cleanup function
useEffect(() => {
const subscription = api.subscribe();
return () => {
subscription.unsubscribe(); // Cleanup on unmount
};
}, []);
// Don't do this (missing dependency)
useEffect(() => {
console.log(count); // ๐ซ count should be in dependency array
}, []);
```
#### useContext - Consume Context
```tsx
// Context definition
interface ThemeContextType {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
// Provider
export const ThemeProvider: FC<{ children: ReactNode }> = ({ children }) => {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
// Custom hook for consuming context
export const useTheme = () => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within ThemeProvider');
}
return context;
};
// Usage in component
const MyComponent = () => {
const { theme, toggleTheme } = useTheme();
return <div className={theme}>...</div>;
};
```
#### useReducer - Complex State
```tsx
interface State {
count: number;
status: 'idle' | 'loading' | 'success' | 'error';
}
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'setLoading' }
| { type: 'setSuccess' }
| { type: 'setError' };
const 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, status: 'loading' };
case 'setSuccess':
return { ...state, status: 'success' };
case 'setError':
return { ...state, status: 'error' };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, {
count: 0,
status: 'idle'
});
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
};
```
#### useMemo - Expensive Computations
```tsx
const ExpensiveComponent = ({ items, filter }: Props) => {
// Only recompute when items or filter changes
const filteredItems = useMemo(() => {
console.log('Filtering items...');
return items.filter(item => item.includes(filter));
}, [items, filter]);
return (
<ul>
{filteredItems.map(item => <li key={item}>{item}</li>)}
</ul>
);
};
```
#### useCallback - Stable Function References
```tsx
const Parent = () => {
const [count, setCount] = useState(0);
const [other, setOther] = useState(0);
// Without useCallback, this function is recreated on every render
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []); // No dependencies = function never changes
// Child won't re-render when 'other' changes
return <MemoizedChild onClick={handleClick} />;
};
const MemoizedChild = memo(({ onClick }: { onClick: () => void }) => {
console.log('Child rendered');
return <button onClick={onClick}>Click</button>;
});
```
#### Custom Hooks
```tsx
// Custom hook for fetching data
function useFetch<T>(url: string) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4โv5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.