React webapp patterns

From Changan-Su/Forsion · View interactive version

React webapp patterns is an AI agent skill from the GitHub repository Changan-Su/Forsion. 当在 Forsion Coding Space 里编写 React/前端组件、hooks、状态管理,或排查重渲染、数据获取、内存泄漏、陈旧闭包类 bug 时使用。提供 hooks 依赖数组、useEffect 竞态与清理、组件组合、状态选型(useState/Context/zustand)、数据获取三态(loading/error/取消)、列表 key、受控/非受控、memo/useMemo/useCallback 的可复制正反例(均适配 importmap+esm.sh 无构建环境)。

How to use this skill

Skill file

Scope: written for Forsion Coding Space's static preview runtime (files served as-is, .ts/.tsx transpiled on the fly, bare imports through an importmap to esm.sh, no bundler, no npm install). In a repository that has its own build system, follow that build system instead of these rules.

React 组件与状态模式

环境=本地 dev-server 即时转译 JSX/TSX,无构建、无 npm install、无打包。裸依赖走项目根 index.html 的 importmap →

https://esm.sh/<包>@<版本>,importmap 必须含 react/jsx-runtime(自动 JSX 运行时),CSS 用 <link> 不在 JS 里 import。

要新增包=加 importmap 条目,不装依赖。下方片段均在此环境直接可跑。本技能只讲怎么写对。

Hooks 铁律(最高频 bug 源)

// 反例:闭包捕获首帧 count,永远只 +1 到 1
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, []); // ← 读了 count 却不进依赖
// 正确:函数式更新,不依赖外部变量,空数组才成立
useEffect(() => {
  const id = setInterval(() => setCount(c => c + 1), 1000);
  return () => clearInterval(id);
}, []);

useEffect 竞态与数据获取(loading / error / 取消)

慢请求先发后到会覆盖新数据。用 AbortController + active 闩锁只认最后一次;用判别联合表达三态,别堆一堆布尔:

type State<T> = { s: 'idle' | 'loading' } | { s: 'ok'; data: T } | { s: 'error'; err: string };

function useUser(id: string) {
  const [st, set] = useState<State<User>>({ s: 'idle' });
  useEffect(() => {
    let active = true;
    const ctrl = new AbortController();
    set({ s: 'loading' });
    fetch(`/api/user/${id}`, { signal: ctrl.signal })
      .then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
      .then(data => { if (active) set({ s: 'ok', data }); })
      .catch(e => { if (active && e.name !== 'AbortError') set({ s: 'error', err: String(e) }); });
    return () => { active = false; ctrl.abort(); }; // id 变化/卸载都取消旧请求
  }, [id]);
  return st;
}

组件组合优于继承

React 里不用类继承共享 UI,而是用 children / 具名插槽 props 拼装,用自定义 hook 抽逻辑。

function Panel({ title, actions, children }:
  { title: string; actions?: React.ReactNode; children: React.ReactNode }) {
  return <section className="panel"><header>{title}{actions}</header>{children}</section>;
}
// <Panel title="用户" actions={<Btn/>}><UserTable/></Panel>

状态管理选型(先本地,按需上升)

| 场景 | 用什么 |

|---|---|

| 只在一个组件/其子树用 | useState / useReducer(多字段联动用 reducer) |

| 少数几层传递 | 直接传 props,别急着上全局 |

| 低频全局:主题、语言、登录用户、feature flag | Context(value 用 useMemo 包稳定) |

| 高频全局:购物车、编辑器文档、协作光标 | zustand(切片订阅,避免全树重渲染) |

import { create } from 'zustand';
export const useCart = create<CartState>((set) => ({
  items: [], add: (it) => set(s => ({ items: [...s.items, it] })),
}));
const count = useCart(s => s.items.length); // 只有 length 变才重渲染;别 const {items}=useCart() 整取

列表 key

受控 vs 非受控

性能:memo 家族(先别加,证明需要再加)

默认不加。多数 memo 化省不了多少,还增加复杂度和 bug 面。只在"确实避免了昂贵计算或大子树重渲染"时加,先用 React DevTools Profiler 测量,别凭感觉。

// 反例:onClick 每帧新建,React.memo(Child) 形同虚设
function List({ items }) {
  return items.map(it => <Child key={it.id} onClick={() => pick(it.id)} />);
}
// 正确:memo 组件 + 稳定回调才生效
const Child = React.memo(function Child({ id, onPick }) { /* 重渲染成本高 */ });
function List({ items, onPick }) {           // onPick 由上层 useCallback 稳定
  return items.map(it => <Child key={it.id} id={it.id} onPick={onPick} />);
}

速查清单

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.