Agent skill

React Hooks Best Practices

by majiayu000 in majiayu000/spellbook

Provides React patterns for hooks, effects, refs, and component design.

MITAuto-check passedFrontend & Design

Install React Hooks Best Practices

skills CLI
$ npx skills add majiayu000/spellbook --skill react-hooks-best-practices -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install majiayu000/spellbook react-hooks-best-practices --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/majiayu000/spellbook.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/react-hooks-best-practices .claude/skills/react-hooks-best-practices && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
react-hooks-best-practices
GitHub stars
287
Token cost
~2.7k tokens
SKILL.md length
280 words
Files
2
Skills in repo
97
Repo updated
First seen
Licence
MIT

At a glance

Provides React patterns for hooks, effects, refs, and component design.

  • Writing React components with hooks
  • SKILL.md covers Pair with TypeScript, Core Principle: Effects Are…, When to Use Effects and When NOT to Use Effects, plus 4 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve React components

What it does

React Hooks Best Practices is an agent skill from majiayu000/spellbook. Provides React patterns for hooks, effects, refs, and component design. Covers escape hatches, anti-patterns, and correct effect usage. Use when reading or writing React components with hooks or effects.

Its SKILL.md is about 2.7k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files (for example `reference/extended.md`).

It sits in Frontend & Design, covering React components. It works with React and TypeScript. The repository describes itself as: Cross-runtime skills for Claude Code, Codex, and multi-agent workflows. The licence is MIT.

When your agent uses it

  • Writing React components with hooks
  • Tasks that involve React components

Example prompts

  • “Use the react-hooks-best-practices skill to provide React patterns for hooks, effects, refs, and component design”
  • “/react-hooks-best-practices”

What it can do on your machine

Read from SKILL.md and the folder at commit ed52af7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

React Hooks Best Practices loads about 2.7k tokens when it runs. Until then it costs about 58 tokens; SKILL.md has 280 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~58
When it runs · the whole SKILL.md, loaded when a task matches
~2.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from majiayu000/spellbook at commit ed52af7, republished under its MIT licence (© majiayu000). 280 words, ~2,679 tokens.

Download SKILL.mdSave it as .claude/skills/react-hooks-best-practices/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
react-hooks-best-practices
description
Provides React patterns for hooks, effects, refs, and component design. Covers escape hatches, anti-patterns, and correct effect usage. Use when reading or writing React components with hooks or effects.

React Hooks Best Practices

Pair with TypeScript

When working with React, always load both this skill and typescript-best-practices together. TypeScript patterns (type-first development, discriminated unions, Zod validation) apply to React code.

Core Principle: Effects Are Escape Hatches

Effects let you "step outside" React to synchronize with external systems. Most component logic should NOT use Effects. Before writing an Effect, ask: "Is there a way to do this without an Effect?"

When to Use Effects

Effects are for synchronizing with external systems:

  • Subscribing to browser APIs (WebSocket, IntersectionObserver, resize)
  • Connecting to third-party libraries not written in React
  • Setting up/cleaning up event listeners on window/document
  • Fetching data on mount (though prefer React Query or framework data fetching)
  • Controlling non-React DOM elements (video players, maps, modals)

When NOT to Use Effects

Derived State (Calculate During Render)
tsx
// BAD: Effect for derived state
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const [fullName, setFullName] = useState('');
useEffect(() => {
  setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);

// GOOD: Calculate during render
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
const fullName = firstName + ' ' + lastName;
Expensive Calculations (Use useMemo)
tsx
// BAD: Effect for caching
const [visibleTodos, setVisibleTodos] = useState([]);
useEffect(() => {
  setVisibleTodos(getFilteredTodos(todos, filter));
}, [todos, filter]);

// GOOD: useMemo for expensive calculations
const visibleTodos = useMemo(
  () => getFilteredTodos(todos, filter),
  [todos, filter]
);
Resetting State on Prop Change (Use key)
tsx
// BAD: Effect to reset state
function ProfilePage({ userId }) {
  const [comment, setComment] = useState('');
  useEffect(() => {
    setComment('');
  }, [userId]);
  // ...
}

// GOOD: Use key to reset component state
function ProfilePage({ userId }) {
  return <Profile userId={userId} key={userId} />;
}

function Profile({ userId }) {
  const [comment, setComment] = useState(''); // Resets automatically
  // ...
}
User Event Handling (Use Event Handlers)
tsx
// BAD: Event-specific logic in Effect
function ProductPage({ product, addToCart }) {
  useEffect(() => {
    if (product.isInCart) {
      showNotification(`Added ${product.name} to cart`);
    }
  }, [product]);
  // ...
}

// GOOD: Logic in event handler
function ProductPage({ product, addToCart }) {
  function buyProduct() {
    addToCart(product);
    showNotification(`Added ${product.name} to cart`);
  }
  // ...
}
Notifying Parent of State Changes
tsx
// BAD: Effect to notify parent
function Toggle({ onChange }) {
  const [isOn, setIsOn] = useState(false);
  useEffect(() => {
    onChange(isOn);
  }, [isOn, onChange]);
  // ...
}

// GOOD: Update both in event handler
function Toggle({ onChange }) {
  const [isOn, setIsOn] = useState(false);
  function updateToggle(nextIsOn) {
    setIsOn(nextIsOn);
    onChange(nextIsOn);
  }
  // ...
}

// BEST: Fully controlled component
function Toggle({ isOn, onChange }) {
  function handleClick() {
    onChange(!isOn);
  }
  // ...
}
Chains of Effects
tsx
// BAD: Effect chain
useEffect(() => {
  if (card !== null && card.gold) {
    setGoldCardCount(c => c + 1);
  }
}, [card]);

useEffect(() => {
  if (goldCardCount > 3) {
    setRound(r => r + 1);
    setGoldCardCount(0);
  }
}, [goldCardCount]);

// GOOD: Calculate derived state, update in event handler
const isGameOver = round > 5;

function handlePlaceCard(nextCard) {
  setCard(nextCard);
  if (nextCard.gold) {
    if (goldCardCount < 3) {
      setGoldCardCount(goldCardCount + 1);
    } else {
      setGoldCardCount(0);
      setRound(round + 1);
    }
  }
}

Effect Dependencies

Never Suppress the Linter
tsx
// BAD: Suppressing linter hides bugs
useEffect(() => {
  const id = setInterval(() => {
    setCount(count + increment);
  }, 1000);
  return () => clearInterval(id);
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// GOOD: Fix the code, not the linter
useEffect(() => {
  const id = setInterval(() => {
    setCount(c => c + increment);
  }, 1000);
  return () => clearInterval(id);
}, [increment]);
Use Updater Functions to Remove State Dependencies
tsx
// BAD: messages in dependencies causes reconnection on every message
useEffect(() => {
  connection.on('message', (msg) => {
    setMessages([...messages, msg]);
  });
  // ...
}, [messages]); // Reconnects on every message!

// GOOD: Updater function removes dependency
useEffect(() => {
  connection.on('message', (msg) => {
    setMessages(msgs => [...msgs, msg]);
  });
  // ...
}, []); // No messages dependency needed
Move Objects/Functions Inside Effects
tsx
// BAD: Object created each render triggers Effect
function ChatRoom({ roomId }) {
  const options = { serverUrl, roomId }; // New object each render
  useEffect(() => {
    const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [options]); // Reconnects every render!
}

// GOOD: Create object inside Effect
function ChatRoom({ roomId }) {
  useEffect(() => {
    const options = { serverUrl, roomId };
    const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId, serverUrl]); // Only reconnects when values change
}
useEffectEvent for Non-Reactive Logic
tsx
// BAD: theme change reconnects chat
function ChatRoom({ roomId, theme }) {
  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.on('connected', () => {
      showNotification('Connected!', theme);
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId, theme]); // Reconnects on theme change!
}

// GOOD: useEffectEvent for non-reactive logic
function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showNotification('Connected!', theme);
  });

  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.on('connected', () => {
      onConnected();
    });
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]); // theme no longer causes reconnection
}
Wrap Callback Props with useEffectEvent
tsx
// BAD: Callback prop in dependencies
function ChatRoom({ roomId, onReceiveMessage }) {
  useEffect(() => {
    connection.on('message', onReceiveMessage);
    // ...
  }, [roomId, onReceiveMessage]); // Reconnects if parent re-renders
}

// GOOD: Wrap callback in useEffectEvent
function ChatRoom({ roomId, onReceiveMessage }) {
  const onMessage = useEffectEvent(onReceiveMessage);

  useEffect(() => {
    connection.on('message', onMessage);
    // ...
  }, [roomId]); // Stable dependency list
}

Effect Cleanup

Always Clean Up Subscriptions
tsx
useEffect(() => {
  const connection = createConnection(serverUrl, roomId);
  connection.connect();
  return () => connection.disconnect(); // REQUIRED
}, [roomId]);

useEffect(() => {
  function handleScroll(e) {
    console.log(window.scrollY);
  }
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll); // REQUIRED
}, []);
Data Fetching with Ignore Flag
tsx
useEffect(() => {
  let ignore = false;

  async function fetchData() {
    const result = await fetchTodos(userId);
    if (!ignore) {
      setTodos(result);
    }
  }

  fetchData();

  return () => {
    ignore = true; // Prevents stale data from old requests
  };
}, [userId]);
Development Double-Fire Is Intentional

React remounts components in development to verify cleanup works. If you see effects firing twice, don't try to prevent it with refs:

tsx
// BAD: Hiding the symptom
const didInit = useRef(false);
useEffect(() => {
  if (didInit.current) return;
  didInit.current = true;
  // ...
}, []);

// GOOD: Fix the cleanup
useEffect(() => {
  const connection = createConnection();
  connection.connect();
  return () => connection.disconnect(); // Proper cleanup
}, []);

Refs

Use Refs for Values That Don't Affect Rendering
tsx
// GOOD: Ref for timeout ID (doesn't affect UI)
const timeoutRef = useRef(null);

function handleClick() {
  clearTimeout(timeoutRef.current);
  timeoutRef.current = setTimeout(() => {
    // ...
  }, 1000);
}

// BAD: Using ref for displayed value
const countRef = useRef(0);
countRef.current++; // UI won't update!
Never Read/Write ref.current During Render
tsx
// BAD: Reading ref during render
function MyComponent() {
  const ref = useRef(0);
  ref.current++; // Mutating during render!
  return <div>{ref.current}</div>; // Reading during render!
}

// GOOD: Read/write refs in event handlers and effects
function MyComponent() {
  const ref = useRef(0);

  function handleClick() {
    ref.current++; // OK in event handler
  }

  useEffect(() => {
    ref.current = someValue; // OK in effect
  }, [someValue]);
}
Ref Callbacks for Dynamic Lists
tsx
// BAD: Can't call useRef in a loop
{items.map((item) => {
  const ref = useRef(null); // Rule violation!
  return <li ref={ref} />;
})}

// GOOD: Ref callback with Map
const itemsRef = useRef(new Map());

{items.map((item) => (
  <li
    key={item.id}
    ref={(node) => {
      if (node) {
        itemsRef.current.set(item.id, node);
      } else {
        itemsRef.current.delete(item.id);
      }
    }}
  />
))}
useImperativeHandle for Controlled Exposure
tsx
// Limit what parent can access
function MyInput({ ref }) {
  const realInputRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focus() {
      realInputRef.current.focus();
    },
    // Parent can ONLY call focus(), not access full DOM node
  }));

  return <input ref={realInputRef} />;
}

Extended Reference

Detailed material starting at ## Custom Hooks has been moved to reference/extended.md to keep this skill concise. Load that reference when the task requires the moved examples, command catalogs, checklists, platform details, or implementation templates.

© majiayu000, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file in skills/react-hooks-best-practices of majiayu000/spellbook.

  • SKILL.md
  • reference/extended.md

Open the folder on GitHubat commit ed52af7

Compare with similar skills

React Hooks Best Practices next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

React Hooks Best Practices compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
React Hooks Best Practices this skillmajiayu000/spellbook287—~2.7kAutomated safety check: PassMIT
Web Artifacts Builderanthropics/skills180k41 repos~769Automated safety check: PassApache-2.0
Dify Component Writing Guidelanggenius/dify158k—~626Automated safety check: PassCustom licence
React Frontend Development Guidelinesdiet103/claude-code-infrastructure-showcase10k2 repos~2.9kAutomated safety check: PassMIT
Formik Form PatternsChrisWiles/claude-code-showcase6.1k3 repos~2.1kAutomated safety check: PassNone
Animated React Component LibrariesHainrixz/editor-pro-max2641 repos~5.7kAutomated safety check: PassCustom licence

Similar skills

  • Web Artifacts Builder

    anthropics/skills

    Official

    Builds multi-component claude.ai HTML artifacts as a small React, TypeScript and Tailwind project, then bundles it into one shareable HTML file.

    180k GitHub starsUsed in 41 repos~769 tokens
    Frontend & DesignAuto-check passed
  • Use when implementing or refactoring React/TypeScript components and the task requires decisions about component ownership, feature boundaries, state, data…

    158k GitHub stars~626 tokensUpdated today
    Frontend & DesignAuto-check passed
  • React Frontend Development Guidelines

    diet103/claude-code-infrastructure-showcase

    Guidelines for React 18 and TypeScript apps covering Suspense data fetching, lazy loading, feature folders, MUI v7 styling, TanStack Router and performance.

    10k GitHub starsUsed in 2 repos~2.9k tokens
    Frontend & DesignAuto-check passed
  • Formik Form Patterns

    ChrisWiles/claude-code-showcase

    Shows how to build forms with Formik and Yup validation, including conditional rules, field helpers, GraphQL submission, edit forms and multi-step flows.

    6.1k GitHub starsUsed in 3 repos~2.1k tokens
    Frontend & DesignAuto-check passed
  • Animated React Component Libraries

    Hainrixz/editor-pro-max

    Helps choose and drop in animated React components from Magic UI and React Bits for landing pages, marketing sites and dashboards, instead of hand-coding animations.

    264 GitHub starsUsed in 1 repo~5.7k tokens
    Frontend & DesignAuto-check passed
  • Fast Typescript Check

    internet-development/www-sacred

    Keep www-sacred's TypeScript fast to type-check and fast to run.

    1.6k GitHub stars~4.3k tokensUpdated yesterday
    Frontend & DesignAuto-check passed

More from majiayu000/spellbook

All 97 skills in this repo
  • Skill Ecosystem Doctor

    majiayu000/spellbook

    Audits and repairs how coding-agent Skills are owned, copied and exposed across runtimes, from canonical sources to quarantine and retirement.

    287 GitHub stars~3k tokensUpdated yesterday
    Auto-check passed
  • AGENTS.md Scaffold

    majiayu000/spellbook

    Scans a repository for real evidence and proposes, or on request writes, a small stack of root and scoped AGENTS.md files with validation commands and generated-file boundaries.

    287 GitHub stars~1.5k tokensUpdated yesterday
    Auto-check passed
  • Product Demo Builder

    majiayu000/spellbook

    Plans, produces or diagnoses evidence-backed product demo videos: script, capture plan, pacing checks and verified final media built on real product behavior.

    287 GitHub stars~3.3k tokensUpdated yesterday
    Auto-check passed
  • Flowguard Task Guard

    majiayu000/spellbook

    Single entry point that routes long or ambiguous agent tasks, checks live state, bounds autonomous loops and leaves a resumable handoff.

    287 GitHub stars~2.1k tokensUpdated yesterday
    Auto-check passed
  • npm Supply Chain Check

    majiayu000/spellbook

    Scans a repository, its lockfiles and node_modules for known malicious npm package versions and install-time indicators, using a read-only Python scanner.

    287 GitHub stars~1.5k tokensUpdated yesterday
    Auto-check passed
  • Product Manager Toolkit

    majiayu000/spellbook

    Product management helpers: a RICE scoring script, an interview transcript analyzer and PRD templates for prioritizing features, synthesizing research and writing requirements.

    287 GitHub stars~2.2k tokensUpdated yesterday
    Auto-check passed

Works with

Questions about React Hooks Best Practices

What does React Hooks Best Practices do?

Provides React patterns for hooks, effects, refs, and component design. React Hooks Best Practices is an agent skill from majiayu000/spellbook. Provides React patterns for hooks, effects, refs, and component design.

When should I use React Hooks Best Practices?

React Hooks Best Practices fits situations like: writing React components with hooks; tasks that involve React components.

How do I install React Hooks Best Practices in Claude Code?

Run `npx skills add majiayu000/spellbook --skill react-hooks-best-practices -a claude-code`. Or copy the skill folder (skills/react-hooks-best-practices in majiayu000/spellbook) into .claude/skills/react-hooks-best-practices in your project. Claude Code loads it when a task matches its description.

How do I install React Hooks Best Practices in Codex?

Run `npx skills add majiayu000/spellbook --skill react-hooks-best-practices -a codex`. Or copy the skill folder (skills/react-hooks-best-practices in majiayu000/spellbook) into .agents/skills/react-hooks-best-practices in your project. Codex loads it when a task matches its description.

Can I use React Hooks Best Practices in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add majiayu000/spellbook --skill react-hooks-best-practices -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/react-hooks-best-practices, .gemini/skills/react-hooks-best-practices, .github/skills/react-hooks-best-practices and .opencode/skills/react-hooks-best-practices in your project.

What does React Hooks Best Practices need to run?

SKILL.md names no scripts, command-line tools or credentials: React Hooks Best Practices is instructions for the agent only.

Does React Hooks Best Practices access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is React Hooks Best Practices safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does React Hooks Best Practices use?

React Hooks Best Practices is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does React Hooks Best Practices use?

About 2.7k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to React Hooks Best Practices?

Skills that share tags, products or a category with React Hooks Best Practices: Web Artifacts Builder (anthropics/skills, 180k stars), Dify Component Writing Guide (langgenius/dify, 158k stars), React Frontend Development Guidelines (diet103/claude-code-infrastructure-showcase, 10k stars) and Formik Form Patterns (ChrisWiles/claude-code-showcase, 6.1k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains React Hooks Best Practices?

majiayu000 (a GitHub user) maintains it in majiayu000/spellbook, which has 287 GitHub stars. The repository holds 97 skills in this directory. The repository was last updated on October 8, 2026.

Source: majiayu000/spellbook on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.