react-hooks
БесплатноБез исполняемых скриптовНе проверенReact Hooks patterns, rules, and custom hook development. Covers all built-in hooks (useState, useEffect, useContext, etc.), performance hooks, and patterns…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
React Hooks
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:reacttopic:hooksfor comprehensive documentation on all React hooks and custom hook patterns.
Built-in Hooks Reference
State Hooks
| Hook | Purpose | When to Use |
|---|---|---|
useState |
Local component state | Simple state values |
useReducer |
Complex state logic | Multiple sub-values, complex updates |
// useState - simple state
const [count, setCount] = useState(0);
const [user, setUser] = useState<User | null>(null);
// useReducer - complex state
type Action = { type: 'increment' } | { type: 'decrement' } | { type: 'reset'; payload: number };
function reducer(state: number, action: Action): number {
switch (action.type) {
case 'increment': return state + 1;
case 'decrement': return state - 1;
case 'reset': return action.payload;
}
}
const [count, dispatch] = useReducer(reducer, 0);
Effect Hooks
| Hook | Purpose | Timing |
|---|---|---|
useEffect |
Side effects, subscriptions | After paint |
useLayoutEffect |
DOM measurements | Before paint |
useInsertionEffect |
CSS-in-JS injection | Before DOM mutations |
// useEffect - most common
useEffect(() => {
const subscription = api.subscribe(id);
return () => subscription.unsubscribe(); // Cleanup
}, [id]); // Dependency array
// useLayoutEffect - measure DOM before paint
useLayoutEffect(() => {
const { height } = ref.current.getBoundingClientRect();
setHeight(height);
}, []);
Context Hook
const ThemeContext = createContext<Theme>('light');
function Component() {
const theme = useContext(ThemeContext); // Reads nearest Provider value
return <div className={theme}>...</div>;
}
Ref Hooks
// DOM reference
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
// Mutable value (no re-render on change)
const renderCount = useRef(0);
renderCount.current++; // Doesn't cause re-render
// useImperativeHandle - customize ref exposed to parent
useImperativeHandle(ref, () => ({
focus: () => inputRef.current?.focus(),
scrollIntoView: () => inputRef.current?.scrollIntoView(),
}), []);
Performance Hooks
// useMemo - cache expensive calculations
const sortedItems = useMemo(() => {
return items.sort((a, b) => a.name.localeCompare(b.name));
}, [items]);
// useCallback - cache function references
const handleClick = useCallback((id: string) => {
setSelected(id);
}, []); // Empty deps = stable reference
// useTransition - non-blocking state updates
const [isPending, startTransition] = useTransition();
startTransition(() => {
setSearchResults(filterLargeList(query)); // Won't block UI
});
// useDeferredValue - defer updating expensive UI
const deferredQuery = useDeferredValue(query);
// UI shows stale value while new value computes
Other Hooks
// useId - unique IDs for accessibility
const id = useId();
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
// useSyncExternalStore - subscribe to external stores
const state = useSyncExternalStore(
store.subscribe,
store.getSnapshot,
store.getServerSnapshot // Optional: for SSR
);
Rules of Hooks
1. Only Call at Top Level
// BAD - conditional hook
if (condition) {
const [value, setValue] = useState(0); // ERROR
}
// BAD - hook in loop
for (const item of items) {
useEffect(() => {}, [item]); // ERROR
}
// GOOD - conditional logic inside hook
const [value, setValue] = useState(0);
useEffect(() => {
if (condition) {
// Do something
}
}, [condition]);
2. Only Call in React Functions
// GOOD - in component
function Component() {
const [state, setState] = useState(0);
}
// GOOD - in custom hook
function useCustomHook() {
const [state, setState] = useState(0);
return state;
}
// BAD - regular function
function helper() {
const [state, setState] = useState(0); // ERROR
}
Custom Hooks Patterns
Basic Pattern
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue] as const;
}
// Usage
const [theme, setTheme] = useLocalStorage('theme', 'dark');
Fetch Hook with Loading/Error States
interface UseFetchResult<T> {
data: T | null;
loading: boolean;
error: Error | null;
refetch: () => void;
}
function useFetch<T>(url: string): UseFetchResult<T> {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
Установить react-hooks в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл react-hooks?
React Hooks patterns, rules, and custom hook development. Covers all built-in hooks (useState, useEffect, useContext, etc.), performance hooks, and patterns for creating reusable custom hooks. USE WHEN: user mentions "custom hooks", "hook rules", "useState", "useEffect", "useReducer", "useCallback", "useMemo", asks about "hook dependencies", "creating hooks", "hook patterns" DO NOT USE FOR: React 19 use() hook - use `react-19` skill instead, Context API details - use `react-context` skill instead, form-specific hooks - use `react-forms` or `react-hook-form` skills instead
Как установить скилл react-hooks?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл react-hooks запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic