关于 react-hooks-complete
面向 React 开发者的 Hooks 指南,覆盖状态、副作用、引用、自定义 Hooks 及 React 19 功能,并提供规则和参考实现。
主要功能
- 01状态与副作用 Hooks
- 02上下文与引用管理
- 03性能优化 Hooks
- 04React 19 并发及表单 Hooks
- 05可复用自定义 Hooks
适用场景
- 01为组件选择合适的 Hook
- 02管理状态并清理副作用
- 03构建可复用的自定义 Hook
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ josiahsiegel/ claude-plugin-marketplace --skill react-hooks-complete安装后在 Claude Code 中输入/react-hooks-complete确认已加载。
附带文件references/custom-hooks-library.mdreferences/performance-and-react-19-hooks.md
详细介绍
快速参考
| Hook | 用途 | 示例 |
|---|---|---|
useState | 本地状态 | const [count, setCount] = useState(0) |
useReducer | 复杂状态 | const [state, dispatch] = useReducer(reducer, init) |
useEffect | 副作用 | useEffect(() => { ... }, [deps]) |
useRef | 可变引用 / DOM | const ref = useRef<HTMLInputElement>(null) |
useContext | 使用上下文 | const value = useContext(MyContext) |
useMemo | 记忆化值 | const computed = useMemo(() => calc(), [deps]) |
useCallback | 稳定函数 | const fn = useCallback(() => {}, [deps]) |
| React 19 Hook | 用途 |
|---|---|
useTransition | 非阻塞更新 |
useDeferredValue | 延迟开销较大的渲染 |
useActionState | Server Action 状态 |
useOptimistic | 乐观 UI 更新 |
useFormStatus | 表单待处理状态 |
何时使用此技能
适用于 React hooks 实现:
- 为使用场景选择合适的 hook
- 使用 useState/useReducer 管理组件状态
- 使用 useEffect 处理副作用和清理
- 构建可复用的自定义 hooks
- 使用 useMemo 和 useCallback 优化
- 使用 React 19 并发特性
对于状态管理库:请参阅 react-state-management
React Hooks 完整指南
状态 Hooks
useState
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
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>
);
}
使用 Immer 的 useReducer
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
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
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(用于 CSS-in-JS 库)
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
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
import { useRef, useEffect } from 'react';
// DOM reference
function TextInput() {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
// Mutable value (doesn't trigger re-render)
function Timer() {
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const [count, setCount] = useState(0);
const startTimer = () => {
if (intervalRef.current) return;
intervalRef.current = setInterval(() => {
setCount((c) => c + 1);
}, 1000);
};
const stopTimer = () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
useEffect(() => {
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
};
}, []);
return (
<div>
<p>Count: {count}</p>
<button onClick={startTimer}>Start</button>
<button onClick={stopTimer}>Stop</button>
</div>
);
}
useImperativeHandle
import { forwardRef, useImperativeHandle, useRef } from 'react';
interface VideoPlayerHandle {
play: () => void;
pause: () => void;
seek: (time: number) => void;
}
const VideoPlayer = forwardRef<VideoPlayerHandle, { src: string }>(
({ src }, ref) => {
const videoRef = useRef<HTMLVideoElement>(null);
useImperativeHandle(ref, () => ({
play() {
videoRef.current?.play();
},
pause() {
videoRef.current?.pause();
},
seek(time: number) {
if (videoRef.current) {
videoRef.current.currentTime = time;
}
},
}));
return <video ref={videoRef} src={src} />;
}
);
// Usage
function App() {
const playerRef = useRef<VideoPlayerHandle>(null);
return (
<div>
<VideoPlayer ref={playerRef} src="/video.mp4" />
<button onClick={() => playerRef.current?.play()}>Play</button>
<button onClick={() => playerRef.current?.pause()}>Pause</button>
<button onClick={() => playerRef.current?.seek(30)}>Skip to 30s</button>
</div>
);
}
性能 Hooks 和 React 19 Hooks
useMemo、useCallback、useTransition、useDeferredValue,以及 React 19 时代的 hooks(如 useActionState、useOptimistic、useFormStatus 和 use)的详细说明位于 references/performance-and-react-19-hooks.md。在优化渲染、处理过渡 / 延迟值,或接入 React 19 表单和异步资源时,请加载该参考资料。
自定义 Hooks
useLocalStorage
import { useState, useEffect } from 'react';
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
if (typeof window === 'undefined') return initialValue;
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error('Failed to save to localStorage:', error);
}
}, [key, value]);
return [value, setValue] as const;
}
// Usage
function App() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Toggle</button>;
}
useDebounce
import { useState, useEffect } from 'react';
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;
}
// Usage
function SearchInput() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 300);
useEffect(() => {
if (debouncedQuery) {
searchAPI(debouncedQuery);
}
}, [debouncedQuery]);
return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}
useFetch
import { useState, useEffect } from 'react';
interface FetchState<T> {
data: T | null;
loading: boolean;
error: Error | null;
}
function useFetch<T>(url: string): FetchState<T> {
const [state, setState] = useState<FetchState<T>>({
data: null,
loading: true,
error: null,
});
useEffect(() => {
let cancelled = false;
const fetchData = async () => {
setState({ data: null, loading: true, error: null });
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (!cancelled) {
setState({ data, loading: false, error: null });
}
} catch (error) {
if (!cancelled) {
setState({
data: null,
loading: false,
error: error instanceof Error ? error : new Error('Unknown error'),
});
}
}
};
fetchData();
return () => {
cancelled = true;
};
}, [url]);
return state;
}
useMediaQuery
import { useState, useEffect } from 'react';
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
setMatches(mediaQuery.matches);
const handler = (event: MediaQueryListEvent) => {
setMatches(event.matches);
};
mediaQuery.addEventListener('change', handler);
return () => mediaQuery.removeEventListener('change', handler);
}, [query]);
return matches;
}
// Usage
function App() {
const isMobile = useMediaQuery('(max-width: 768px)');
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
return (
<div className={prefersDark ? 'dark' : 'light'}>
{isMobile ? <MobileNav /> : <DesktopNav />}
</div>
);
}
Hooks 规则
- 仅在顶层调用 hooks - 不要在循环、条件语句或嵌套函数中调用
- 仅从 React 函数中调用 hooks - 从组件或自定义 hooks 中调用
- 自定义 hook 名称以 "use" 开头 - 这是便于 lint 检查的约定
// Bad - conditional hook call
function Bad({ condition }) {
if (condition) {
const [state, setState] = useState(0); // Error!
}
}
// Good - call hook unconditionally
function Good({ condition }) {
const [state, setState] = useState(0);
if (condition) {
// Use state here
}
}
更多参考资料
如需适用于生产环境的自定义 hook 实现,请参阅:
references/custom-hooks-library.md- 可复用自定义 hooks 的完整库
评论
支持 Markdown