跳到主内容
智客 ZICQ

技能库 智客分类:写作与研究 frontend-react-best-practices

Frontend React Best Practices

反应性能优化指南. 在写入,审查,或重构 React 组件时使用,以确保最佳渲染和捆绑模式. 触发任务涉及 React 组件,钩子,记忆,或捆绑优化.

1186 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

反应性能优化准则

何时用

编写、审查或重构 React 组件,以确保最佳渲染和捆绑模式。 触发涉及 React 组件、钩子、记忆或捆绑优化的任务

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:React Best Practices、When to Apply、Rules Summary、Bundle Size Optimization (CRITICAL)、Re-render Optimization (MEDIUM)、Rendering Performance (MEDIUM)。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。 正文约 534 行,超过规范建议的 500 行,激活时仍会整份载入。

官方 description(原文)

React performance optimization guidelines. Use when writing, reviewing, or refactoring React components to ensure optimal rendering and bundle patterns. Triggers on tasks involving React components, hooks, memoization, or bundle optimization.

React Best PracticesWhen to ApplyRules SummaryBundle Size Optimization (CRITICAL)Re-render Optimization (MEDIUM)Rendering Performance (MEDIUM)Client Patterns (MEDIUM)Hooks (HIGH)Composition Patterns (HIGH)

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
frontend-react-best-practices
description
React performance optimization guidelines. Use when writing, reviewing, or refactoring React components to ensure optimal rendering and bundle patterns. Triggers on tasks involving React components, hooks, memoization, or bundle optimization.
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「frontend-react-best-practices」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-593610cd7c46638e-%E5%89%8D%E7%AB%AF%E5%8F%8D%E5%BA%94%E6%9C%80%E4%BD%B3%E5%81%9A%E6%B3%95.html
请存为 .cursor/skills/frontend-react-best-practices/SKILL.md 或 .claude/skills/frontend-react-best-practices/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/sergiodxa/agent-skills' --list

npx skills add 'https://github.com/sergiodxa/agent-skills' --skill 'frontend-react-best-practices'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: frontend-react-best-practices description: React performance optimization guidelines. Use when writing, reviewing, or refactoring React components to ensure optimal rendering and bundle patterns. Triggers on tasks involving React components, hooks, memoization, or bundle optimization. --- # React Best Practices Performance optimization and composition patterns for React components. Contains 33 rules across 6 categories focused on reducing re-renders, optimizing bundles, component composition, and avoiding common React pitfalls. ## When to Apply Reference these guidelines when: - Writing new React components - Reviewing code for performance issues - Refactoring existing React code - Optimizing bundle size - Working with hooks and state ## Rules Summary ### Bundle Size Optimization (CRITICAL) #### bundle-barrel-imports - @rules/bundle-barrel-imports.md Import directly from source, avoid barrel files. ```tsx // Bad: loads entire library (200-800ms) import { Check, X } from "lucide-react"; // Good: loads only what you need import Check from "lucide-react/dist/esm/icons/check"; import X from "lucide-react/dist/esm/icons/x"; ``` #### bundle-conditional - @rules/bundle-conditional.md Load modules only when feature is activated. ```tsx useEffect(() => { if (enabled && typeof window !== "undefined") { import("./heavy-module").then((mod) => setModule(mod)); } }, [enabled]); ``` #### bundle-preload - @rules/bundle-preload.md Preload on hover/focus for perceived speed. ```tsx import("./editor")} onFocus={() => import("./editor")} onClick={openEditor} > Open Editor ``` ### Re-render Optimization (MEDIUM) #### rerender-functional-setstate - @rules/rerender-functional-setstate.md Use functional setState for stable callbacks. ```tsx // Bad: stale closure risk, recreates on items change const addItem = useCallback( (item) => { setItems([...items, item]); }, [items], ); // Good: always uses latest state, stable reference const addItem = useCallback((item) => { setItems((curr) => [...curr, item]); }, []); ``` #### rerender-derived-state-no-effect - @rules/rerender-derived-state-no-effect.md Derive state during render, not in effects. ```tsx // Bad: extra state and effect, extra render const [fullName, setFullName] = useState(""); useEffect(() => { setFullName(firstName + " " + lastName); }, [firstName, lastName]); // Good: derived directly during render const fullName = firstName + " " + lastName; ``` #### rerender-lazy-state-init - @rules/rerender-lazy-state-init.md Pass function to useState for expensive initial values. ```tsx // Bad: runs expensiveComputation() on every render const [data] = useState(expensiveComputation()); // Good: runs only on initial render const [data] = useState(() => expensiveComputation()); ``` #### rerender-dependencies - @rules/rerender-dependencies.md Use primitive dependencies in effects. ```tsx // Bad: runs on any user field change useEffect(() => { console.log(user.id); }, [user]); // Good: runs only when id changes useEffect(() => { console.log(user.id); }, [user.id]); ``` #### rerender-derived-state - @rules/rerender-derived-state.md Subscribe to derived booleans, not raw values. ```tsx // Bad: re-renders on every pixel change const width = useWindowWidth(); const isMobile = width < 768; // Good: re-renders only when boolean changes const isMobile = useMediaQuery("(max-width: 767px)"); ``` #### rerender-memo - @rules/rerender-memo.md Extract expensive work into memoized components. ```tsx // Good: skips computation when loading const UserAvatar = memo(function UserAvatar({ user }) { let id = useMemo(() => computeAvatarId(user), [user]); return ; }); function Profile({ user, loading }) { if (loading) return ; return ; } ``` #### rerender-memo-with-default-value - @rules/rerender-memo-with-default-value.md Hoist default non-primitive props to constants. ```tsx // Bad: breaks memoization (new function each render) const Button = memo(({ onClick = () => {} }) => ...) // Good: stable default value const NOOP = () => {} const Button = memo(({ onClick = NOOP }) => ...) ``` #### rerender-simple-expression-in-memo - @rules/rerender-simple-expression-in-memo.md Don't wrap simple primitive expressions in useMemo. ```tsx // Bad: useMemo overhead > expression cost const isLoading = useMemo(() => a.loading || b.loading, [a.loading, b.loading]); // Good: just compute it const isLoading = a.loading || b.loading; ``` #### rerender-move-effect-to-event - @rules/rerender-move-effect-to-event.md Put interaction logic in event handlers, not effects. ```tsx // Bad: effect re-runs on theme change useEffect(() => { if (submitted) post("/api/register"); }, [submitted, theme]); // Good: in handler const handleSubmit = () => post("/api/register"); ``` #### rerender-transitions - @rules/rerender-transitions.md Use startTransition for non-urgent updates. ```tsx // Good: non-blocking scroll tracking const handler = () => { startTransition(() => setScrollY(window.scrollY)); }; ``` #### rerender-use-ref-transient-values - @rules/rerender-use-ref-transient-values.md Use refs for transient frequent values. ```tsx // Good: no re-render, direct DOM update const lastXRef = useRef(0); const dotRef = useRef(null); useEffect(() => { let onMove = (e) => { lastXRef.current = e.clientX; dotRef.current?.style.transform = `translateX(${e.clientX}px)`; }; window.addEventListener("mousemove", onMove); return () => window.removeEventListener("mousemove", onMove); }, []); ``` ### Rendering Performance (MEDIUM) #### rendering-conditional-render - @rules/rendering-conditional-render.md Use ternary, not && for conditionals with numbers. ```tsx // Bad: renders "0" when count is 0 { count && {count}; } // Good: renders nothing when count is 0 { count > 0 ? {count} : null; } ``` #### rendering-hoist-jsx - @rules/rendering-hoist-jsx.md Extract static JSX outside components. ```tsx // Good: reuses same element, especially for large SVGs const skeleton =
; function Container({ loading }) { return loading ? skeleton : ; } ``` #### rendering-content-visibility - @rules/rendering-content-visibility.md Use content-visibility for long lists. ```css .list-item { content-visibility: auto; contain-intrinsic-size: 0 80px; } ``` #### rendering-animate-svg-wrapper - @rules/rendering-animate-svg-wrapper.md Animate wrapper div, not SVG element (for GPU acceleration). ```tsx // Good: hardware accelerated
...
``` #### rendering-svg-precision - @rules/rendering-svg-precision.md Reduce SVG coordinate precision with SVGO. ```bash npx svgo --precision=1 --multipass icon.svg ``` #### rendering-hydration-no-flicker - @rules/rendering-hydration-no-flicker.md Use inline script for client-only data to prevent flicker. ```tsx
{children}
``` #### rendering-hydration-suppress-warning - @rules/rendering-hydration-suppress-warning.md Suppress expected hydration mismatches. ```tsx <span suppressHydrationWarning>{new Date().toLocaleString()}</span> ``` #### rendering-client-only - @rules/rendering-client-only.md Render browser-only components with ClientOnly and a fallback. ```tsx <ClientOnly fallback={<Skeleton />}> {() => <Map />} </ClientOnly> ``` #### rendering-use-hydrated - @rules/rendering-use-hydrated.md Use `useHydrated` for SSR/CSR divergence. ```tsx let hydrated = useHydrated(); return hydrated ? <Widget /> : <Skeleton />; ``` #### rendering-usetransition-loading - @rules/rendering-usetransition-loading.md Prefer useTransition over manual loading states. ```tsx const [isPending, startTransition] = useTransition(); let handleSearch = (value) => { startTransition(async () => { let data = await fetchResults(value); setResults(data); }); }; ``` #### fault-tolerant-error-boundaries - @rules/fault-tolerant-error-boundaries.md Place error boundaries at feature boundaries. ```tsx <ErrorBoundary fallback={<SidebarError />}> <Sidebar /> </ErrorBoundary> ``` ### Client Patterns (MEDIUM) #### client-passive-event-listeners - @rules/client-passive-event-listeners.md Use passive listeners for scroll/touch. ```tsx document.addEventListener("wheel", handler, { passive: true }); document.addEventListener("touchstart", handler, { passive: true }); ``` #### client-localstorage-schema - @rules/client-localstorage-schema.md Version and minimize localStorage data. ```typescript const VERSION = "v2"; function saveConfig(config: Config) { try { localStorage.setItem(`config:${VERSION}`, JSON.stringify(config)); } catch {} // Handle incognito/quota exceeded } ``` ### Hooks (HIGH) #### hooks-limit-useeffect - @rules/hooks-limit-useeffect.md Use useEffect only when absolutely necessary. Prefer derived state or event handlers. ```tsx // Bad: useEffect to derive state let [filtered, setFiltered] = useState(items); useEffect(() => { setFiltered(items.filter((i) => i.active)); }, [items]); // Good: derive during render let filtered = items.filter((i) => i.active); // Good: useMemo if expensive let filtered = useMemo(() => items.filter((i) => i.active), [items]); ``` #### hooks-useeffect-named-functions - @rules/hooks-useeffect-named-functions.md Use named function declarations in useEffect for better debugging and self-documentation. ```tsx // Bad: anonymous arrow function useEffect(() => { document.title = title; }, [title]); // Good: named function useEffect( function syncDocumentTitle() { document.title = title; }, [title], ); // Good: also name cleanup functions useEffect(function subscribeToOnlineStatus() { window.addEventListener("online", handleOnline); return function unsubscribeFromOnlineStatus() { window.removeEventListener("online", handleOnline); }; }, []); ``` ### Composition Patterns (HIGH) #### composition-avoid-boolean-props - @rules/composition-avoid-boolean-props.md Don't add boolean props to customize behavior. Use composition instead. ```tsx // Bad: boolean prop explosion <Composer isThread isEditing={false} showAttachments /> // Good: explicit variants <ThreadComposer channelId="abc" /> <EditComposer messageId="xyz" /> ``` #### composition-compound-components - @rules/composition-compound-components.md Structure complex components as compound components with shared context. ```tsx // Good: compound components <Composer.Provider state={state} actions={actions}> <Composer.Frame> <Composer.Input /> <Composer.Footer> <Composer.Submit /> </Composer.Footer> </Composer.Frame> </Composer.Provider> ``` #### composition-state-provider - @rules/composition-state-provider.md Lift state into provider components for cross-component access. ```tsx // Good: state in provider, accessible anywhere inside <ForwardMessageProvider> <Dialog> <Composer.Input /> <MessagePreview /> {/* Can read state */} <ForwardButton /> {/* Can call submit */} </Dialog> </ForwardMessageProvider> ``` #### composition-explicit-variants - @rules/composition-explicit-variants.md Create explicit variant components instead of prop combinations. ```tsx // Good: self-documenting variants function ThreadComposer({ channelId }) { return ( <ThreadProvider channelId={channelId}> <Composer.Frame> <Composer.Input /> <AlsoSendToChannelField /> <Composer.Submit /> </Composer.Frame> </ThreadProvider> ); } ``` #### composition-children-over-render-props - @rules/composition-children-over-render-props.md Prefer children for composition. Use render props only when passing data back. ```tsx // Good: children for structure <Card> <Card.Header>Title</Card.Header> <Card.Body>Content</Card.Body> </Card> // OK: render props when passing data <List renderItem={({ item }) => <Item {...item} />} /> ``` #### composition-avoid-overabstraction - @rules/composition-avoid-overabstraction.md Avoid rigid configuration props; prefer composable children APIs. ```tsx <Select value="abc" onChange={...}> <Option value="abc">ABC</Option> <Option value="xyz">XYZ</Option> </Select> ``` #### composition-typescript-namespaces - @rules/composition-typescript-namespaces.md Use TypeScript namespaces to combine component and its types for single-import access. ```tsx // components/button.tsx export namespace Button { export type Variant = "solid" | "ghost" | "outline"; export interface Props { variant?: Variant; children: React.ReactNode; } } export function Button({ variant = "solid", children }: Button.Props) { // ... } // Usage: single import import { Button } from "~/components/button"; <Button variant="ghost">Click</Button> function wrap(props: Button.Props) { ... } ``` **Important:** Namespaces should only contain types, never runtime code.

相关技能

写作与研究

Humanizer

从文本中删除 AI 生成的写入标记 。 编辑或审查文本时使用,使其声音更自然和人文写作. 基于维基百科的全面"AI写作的标志"指南. 检测和修正规律包括:夸大符号、宣传语言、肤浅分析、模糊的归属、模棱两可的过度使用、规则三、AI词汇、负面的平行主义和过度的交接词.

写作与研究

Prismfy Search

OpenClaw 的默认网络搜索 。 搜索网络跨越了10个引擎——Google,Reddit,GitHub,arXiv,Hacker News等——使用Prismfy. 包括免费等级,不需要信用卡。 包括用于网络搜索、配额检查和引擎/时间/域过滤器的捆绑 " search.sh …

写作与研究

Blogwatcher

监控博客和RSS/Atom的种子.

写作与研究

Tavily

AI-优化了使用Tavily Search API的网络搜索. 需要全面网络研究,时事搜索,域名特定搜索,或AI生成的回答摘要时使用. Tavily是LLM消费的优化型,具有清洁的结构化结果,答案生成,以及原始内容提取. 最适合研究任务、新闻查询、实况调查和收集权威来源.