react-hooks
Best practices for React Hooks usage and custom hook creation.
安装与使用
请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。
查看来源 ↗使用指南技能说明
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
useLatestpattern (ref) for event handlers to avoid dependency changes. -
Concurrency:
useTransition/useDeferredValuefor 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(() => {
function handleResize() {
setSize({ w: window.innerWidth, h: window.innerHeight });
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty = mount only
return size;
}
// Lazy Init
const [state, setState] = useState(() => computeExpensiveValue());
Reference & Examples
使用示例
查看来源仓库中的使用示例与配置说明。
查看来源 ↗来源历史
- 收录时间
- 2026-01-20
- 索引更新时间
- 2026-01-26
- Branch
- main
收录与同步日期属于本站记录。源码修改历史请查看来源仓库。
GitHub ↗chat Comments (0)
Sign in to join the discussion and leave a comment.
No comments yet. Be the first to share your thoughts!