金色时刻 · 15:48
让好资源,触手可及
AGENT SKILL

hooks

hooks 是面向效率工具、软件开发的 Agent Skill,来自 HoangNguyen0403/agent-skills-standard。查看技能说明、操作步骤与使用约定,并通过原项目了解详细用法。

Best practices for React Hooks usage and custom hook creation.

SKILL.md

下载 MD ↓
nameReact Hooks
descriptionBest practices for React Hooks usage and custom hook creation.
metadata{"labels": ["react", "hooks", "custom-hooks", "useeffect"], "triggers": {"files": ["**/*.tsx", "**/*.jsx"], "keywords": ["useEffect", "useCallback", "useMemo", "useRef", "custom hook"]}}

React Hooks

Priority: P1 (OPERATIONAL)

Effective usage of React Hooks.

Implementation Guidelines

  • Rules: Top-level only. Only in React functions.
  • useEffect: Sync with external systems ONLY. Cleanup required.
  • useRef: Mutable state without re-renders (DOM, timers, tracking).
  • useMemo/Callback: Measure first. Use for stable refs or heavy computation.
  • Dependencies: Exhaustive deps always. Fix logic, don't disable linter.
  • Custom Hooks: Extract shared logic. Prefix use*.
  • Refs as Escape Hatch: Access imperative APIs (focus, scroll).
  • Stability: Use useLatest pattern (ref) for event handlers to avoid dependency changes.
  • Concurrency: useTransition / useDeferredValue for non-blocking UI updates.
  • Initialization: Lazy state useState(() => expensive()).

Anti-Patterns

  • No Effects for Data Flow: Derive state in render.
  • No Missing Deps: Causes stale closures.
  • No Complex Effects: Split into multiple simple effects.
  • No Oversubscription: Check why-did-you-render.

Code

// Custom Hook
function useWindowSize() {
  const [size, setSize] = useState({ w: 0, h: 0 });

  useEffect(() => {
    const onResize = () =>
      setSize({ w: window.innerWidth, h: window.innerHeight });
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []); // Empty = mount only

  return size;
}

// Lazy Init
const [state, setState] = useState(() => computeExpensiveValue());

Reference & Examples

See references/REFERENCE.md.

来源:HoangNguyen0403/agent-skills-standard · MIT 许可 · 许可原文 · MD 为来源页保存的历史版本