Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

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от claude-dev-suite★ 51 звезда на GitHub

Об этом скилле

React Hooks

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: react topic: hooks for 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 {
Полный SKILL.md на GitHub

Установить react-hooks в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Grep
Glob
Write
Edit

Вложенные файлы

quick-ref/hooks-cheatsheet.md

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), без исполняемых скриптов.

Похожие скиллы

Сравнить react-hooks с