Token导航 LogoToken导航TokenDH.com
开发操作浏览器github未标认证来源可访问许可证需确认审计通过

react-useeffectReact useeffect 开发

Agent Skill

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

总安装

423

周安装

18

GitHub Stars

公开资料未说明

下载量

148
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:react-useeffect(React useeffect 开发)
来源仓库:https://github.com/b4r7x/agent-skills
仓库路径:skills/react-useeffect
安装命令:
npx skills add https://github.com/b4r7x/agent-skills --skill react-useeffect
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/b4r7x/agent-skills --skill react-useeffect

简介

react-useeffect 指导合理使用 useEffect,避免不必要的副作用,提升组件性能与可维护性。

  • 适用于在 Codex、Claude、Cursor、Gemini CLI 中编写或审查 React 组件中的副作用逻辑。
  • 提供决策树帮助用户判断何时使用事件、渲染计算还是 effect,强调“无外部系统则无需 effect”。
  • 安装方式:npx skills add https://github.com/b4r7x/agent-skills --skill react-useeffect。
  • 使用前需确认权限范围、维护状态,并注意是否会触发联网、命令执行或文件读写操作。

SKILL.md

React useEffect

Overview

useEffect is an escape hatch — it synchronizes a component with an external system. If there's no external system involved, you probably don't need an effect.

"Code that runs because a component was displayed should be in Effects. The rest should be in events." — React docs

Decision Tree

Code you want to run...
  ├─ User clicked / submitted / performed action?
  │         → Event handler
  ├─ Derivable from existing state/props?
  │         → Compute during render (or useMemo)
  ├─ Need to reset state when a prop changes?
  │         → key on the component
  ├─ Need to notify parent about state change?
  │         → Call callback in the same event handler
  └─ Component is visible and must sync with something
     OUTSIDE React (DOM, network, timer, library)?
              → useEffect ✅

Valid Use Cases

1. External system connection

useEffect(() => {
  const conn = createConnection(serverUrl, roomId);
  conn.connect();
  return () => conn.disconnect(); // always cleanup
}, [serverUrl, roomId]);

2. Browser event subscription

useEffect(() => {
  const handler = () => setIsOnline(navigator.onLine);
  window.addEventListener('online', handler);
  window.addEventListener('offline', handler);
  return () => {
    window.removeEventListener('online', handler);
    window.removeEventListener('offline', handler);
  };
}, []);

Consider useSyncExternalStore as a less error-prone alternative.

3. Data fetch (without framework)

// Option A: ignore flag
useEffect(() => {
  let ignore = false;
  fetchUser(userId).then(data => {
    if (!ignore) setUser(data);
  });
  return () => { ignore = true; };
}, [userId]);

// Option B: AbortController (preferred — actually cancels the request)
useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then(r => r.json())
    .then(setUser)
    .catch(err => {
      if (err.name !== 'AbortError') setError(err);
    });
  return () => controller.abort();
}, [userId]);

If using a framework (Next.js, Remix) — use its data fetching mechanism instead.

4. Non-React library integration (D3, maps, video)

5. Analytics (logging page views)

6. Server/client rendering differences

function ClientOnlyComponent() {
  const [isClient, setIsClient] = useState(false);
  useEffect(() => { setIsClient(true); }, []);
  if (!isClient) return <ServerFallback />;
  return <div>{localStorage.getItem('theme')}</div>;
}

Anti-patterns

1. Derived state (most common mistake)

// ❌ Two unnecessary renders
const [total, setTotal] = useState(0);
useEffect(() => {
  setTotal(items.reduce((sum, i) => sum + i.price, 0));
}, [items]);

// ✅ Compute during render
const total = items.reduce((sum, i) => sum + i.price, 0);

2. Event-specific logic

// ❌ Notification fires on every page refresh
useEffect(() => {
  if (product.isInCart) showNotification(`Added ${product.name}!`);
}, [product]);

// ✅ Logic in event handler — only when user clicks
function handleBuyClick() {
  addToCart(product);
  showNotification(`Added ${product.name}!`);
}

3. Chains of effects

// ❌ 3 effects, each triggering the next = 3 unnecessary renders
useEffect(() => { if (card?.gold) setGoldCount(c => c + 1); }, [card]);
useEffect(() => { if (goldCount > 3) { setRound(r => r + 1); setGoldCount(0); } }, [goldCount]);
useEffect(() => { if (round > 5) setIsGameOver(true); }, [round]);

// ✅ All logic in one event handler — single render
function handlePlaceCard(nextCard) {
  setCard(nextCard);
  if (nextCard.gold) {
    if (goldCount < 3) setGoldCount(goldCount + 1);
    else { setGoldCount(0); setRound(round + 1); }
  }
}
const isGameOver = round > 5; // derived, not state

4. Notifying parent via effect

// ❌ Double render
useEffect(() => { onChange(isOn); }, [isOn, onChange]);

// ✅ Both states in one interaction
function handleClick() {
  const next = !isOn;
  setIsOn(next);
  onChange(next); // immediately, in same event
}

5. Resetting state via effect

// ❌ Renders with stale state first, then resets
useEffect(() => { setComment(''); }, [userId]);

// ✅ key forces React to reset all state
<Profile key={userId} userId={userId} />

6. Adjusting state when props/state change via effect

// ❌ Extra render cycle — renders stale UI, commits to DOM, then re-renders
useEffect(() => {
  if (error) setOtpValue("");
}, [error]);

// ✅ Adjust state during render (documented React pattern)
// React skips the stale commit — clears value before painting
const [prevState, setPrevState] = useState(state);
if (state !== prevState) {
  setPrevState(state);
  if (error) setOtpValue("");
}

This is the "Storing information from previous renders" pattern from the official React useState docs. Key rules:

  • Use useState (not useRef) to store the previous value — ref mutation during render is a side effect
  • Guard with an if condition to avoid infinite loops
  • Prefer deriving values or using key when possible — this is a last resort
  • See: useState — Storing information from previous renders

7. App initialization

// ❌ Runs twice in Strict Mode
useEffect(() => { checkAuthToken(); }, []);

// ✅ Module-level (runs once on import)
if (typeof window !== 'undefined') { checkAuthToken(); }

Dependency Pitfalls

Object as dependency

// ❌ New object every render = effect runs every render
const options = { serverUrl, roomId };
useEffect(() => { /* ... */ }, [options]);

// ✅ Create object inside effect
useEffect(() => {
  const options = { serverUrl, roomId };
  // ...
}, [roomId]); // only primitive deps

Functional updater to avoid deps

// ❌ count in deps = reset interval on every change
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, [count]);

// ✅ Functional update — no count in deps
useEffect(() => {
  const id = setInterval(() => setCount(c => c + 1), 1000);
  return () => clearInterval(id);
}, []);

Cleanup Checklist

Every effect that subscribes, connects, or sets a timer must return a cleanup function:

  • setIntervalclearInterval
  • addEventListenerremoveEventListener
  • WebSocket connect → disconnect
  • fetchAbortController.abort() or ignore flag

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.88%
按下载量换算52

Claude

27.8%
按下载量换算41

Cursor

18.07%
按下载量换算27

Gemini CLI

9.49%
按下载量换算14

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills