react-hooks-complete
Complete React hooks reference system. PROACTIVELY activate for: (1) useState and useReducer patterns, (2) useEffect and lifecycle, (3) useRef for DOM and values, (4) useContext for shared state, (5) useMemo and useCallback optimization, (6) React 19 hooks (useTransition, useDeferredValue, useActionState, useOptimistic), (7) Custom hook development, (8) Hook rules and best practices. Provides: Hook syntax, effect cleanup patterns, performance optimization, custom hook patterns. Ensures correct hook usage following React best practices.
What this skill does
## Quick Reference
| Hook | Purpose | Example |
|------|---------|---------|
| `useState` | Local state | `const [count, setCount] = useState(0)` |
| `useReducer` | Complex state | `const [state, dispatch] = useReducer(reducer, init)` |
| `useEffect` | Side effects | `useEffect(() => { ... }, [deps])` |
| `useRef` | Mutable ref / DOM | `const ref = useRef<HTMLInputElement>(null)` |
| `useContext` | Consume context | `const value = useContext(MyContext)` |
| `useMemo` | Memoize value | `const computed = useMemo(() => calc(), [deps])` |
| `useCallback` | Stable function | `const fn = useCallback(() => {}, [deps])` |
| React 19 Hook | Purpose |
|---------------|---------|
| `useTransition` | Non-blocking updates |
| `useDeferredValue` | Defer expensive renders |
| `useActionState` | Server Action state |
| `useOptimistic` | Optimistic UI updates |
| `useFormStatus` | Form pending state |
## When to Use This Skill
Use for **React hooks implementation**:
- Choosing the right hook for your use case
- Managing component state with useState/useReducer
- Handling side effects and cleanup with useEffect
- Building custom reusable hooks
- Optimizing with useMemo and useCallback
- Using React 19 concurrent features
**For state management libraries**: see `react-state-management`
---
# React Hooks Complete Guide
## State Hooks
### useState
```tsx
import { useState } from 'react';
// Basic usage
const [count, setCount] = useState(0);
// With initial function (lazy initialization)
const [state, setState] = useState(() => {
const initialValue = expensiveComputation();
return initialValue;
});
// Object state
const [user, setUser] = useState<User | null>(null);
// Updating object state (always create new reference)
setUser((prev) => prev ? { ...prev, name: 'New Name' } : null);
// Array state
const [items, setItems] = useState<Item[]>([]);
// Add item
setItems((prev) => [...prev, newItem]);
// Remove item
setItems((prev) => prev.filter((item) => item.id !== id));
// Update item
setItems((prev) =>
prev.map((item) => (item.id === id ? { ...item, ...updates } : item))
);
```
### useReducer
```tsx
import { useReducer } from 'react';
// Define state and action types
interface State {
count: number;
error: string | null;
loading: boolean;
}
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'reset'; payload: number }
| { type: 'setError'; payload: string };
// Reducer function
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 'reset':
return { ...state, count: action.payload };
case 'setError':
return { ...state, error: action.payload };
default:
return state;
}
}
// Usage
function Counter() {
const [state, dispatch] = useReducer(reducer, {
count: 0,
error: null,
loading: false,
});
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset', payload: 0 })}>
Reset
</button>
</div>
);
}
```
### useReducer with Immer
```tsx
import { useReducer } from 'react';
import { produce } from 'immer';
interface Todo {
id: number;
text: string;
completed: boolean;
}
type Action =
| { type: 'add'; text: string }
| { type: 'toggle'; id: number }
| { type: 'delete'; id: number };
function todosReducer(state: Todo[], action: Action): Todo[] {
return produce(state, (draft) => {
switch (action.type) {
case 'add':
draft.push({
id: Date.now(),
text: action.text,
completed: false,
});
break;
case 'toggle':
const todo = draft.find((t) => t.id === action.id);
if (todo) todo.completed = !todo.completed;
break;
case 'delete':
const index = draft.findIndex((t) => t.id === action.id);
if (index !== -1) draft.splice(index, 1);
break;
}
});
}
```
## Effect Hooks
### useEffect
```tsx
import { useEffect, useState } from 'react';
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
async function fetchUser() {
setLoading(true);
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
if (!cancelled) {
setUser(data);
}
} catch (error) {
if (!cancelled) {
console.error('Failed to fetch user:', error);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
fetchUser();
// Cleanup function
return () => {
cancelled = true;
};
}, [userId]); // Re-run when userId changes
if (loading) return <p>Loading...</p>;
if (!user) return <p>User not found</p>;
return <div>{user.name}</div>;
}
```
### useLayoutEffect
```tsx
import { useLayoutEffect, useRef, useState } from 'react';
function Tooltip({ text, children }: { text: string; children: ReactNode }) {
const [tooltipHeight, setTooltipHeight] = useState(0);
const tooltipRef = useRef<HTMLDivElement>(null);
// Runs synchronously after DOM mutations but before paint
useLayoutEffect(() => {
if (tooltipRef.current) {
setTooltipHeight(tooltipRef.current.getBoundingClientRect().height);
}
}, [text]);
return (
<div className="tooltip-container">
{children}
<div
ref={tooltipRef}
className="tooltip"
style={{ top: -tooltipHeight - 10 }}
>
{text}
</div>
</div>
);
}
```
### useInsertionEffect (for CSS-in-JS libraries)
```tsx
import { useInsertionEffect } from 'react';
// For CSS-in-JS library authors
function useCSS(rule: string) {
useInsertionEffect(() => {
const style = document.createElement('style');
style.textContent = rule;
document.head.appendChild(style);
return () => {
document.head.removeChild(style);
};
}, [rule]);
}
```
## Context Hook
### useContext
```tsx
import { createContext, useContext, useState, ReactNode } from 'react';
// Define context type
interface AuthContextType {
user: User | null;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
isAuthenticated: boolean;
}
// Create context with default value
const AuthContext = createContext<AuthContextType | null>(null);
// Provider component
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const login = async (email: string, password: string) => {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
});
const userData = await response.json();
setUser(userData);
};
const logout = () => {
setUser(null);
};
return (
<AuthContext.Provider
value={{
user,
login,
logout,
isAuthenticated: !!user,
}}
>
{children}
</AuthContext.Provider>
);
}
// Custom hook for using context
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
// Usage
function LoginButton() {
const { isAuthenticated, logout, user } = useAuth();
if (isAuthenticated) {
return (
<div>
<span>Welcome, {user?.name}</span>
<button onClick={logout}>Logout</button>
</div>
);
}
return <Link href="/login">Login</Link>;
}
```
## Ref Hooks
### useRef
```tsx
import { useRef, useEffect } frRelated 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.