Logo vun React Style

React Style

Communautéit
happydog-intj
react-style

React 核心源码编码风格 Skill。蒸馏自 facebook/react 核心包(packages/react-dom、 packages/react-reconciler、packages/scheduler),以及 Dan Abramov、Sebastian Markbåge、 Andrew Clark 的 PR review 和设计文档。 触发词:「React 源码风格」「Fiber 架构」「reconciler 风格」「react core style」「React 内部实现」。 适用:React 核心贡献、自定义 reconciler、调度器集成、Fiber 树遍历、effects 系统开发。

Iwwersiicht

Editeurhappydog-intj
Repositoryluban-skill
Skill-Nummreact-style
Stären
32
Forks
3
Matgeliwwert Fichieren
Nëmmen Instruktiounen
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    Vum happydog-intj op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill React Style an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/happydog-intj/luban-skill/tree/master/skills/react.skill
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/happydog-intj/luban-skill.git /tmp/luban-skill
mkdir -p .claude/skills
cp -r /tmp/luban-skill/skills/react.skill .claude/skills/react-style
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert React Style an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet React Style automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass React Style net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

React 核心 · 编码 DNA

"Conceptual integrity matters more than individual pieces." — Sebastian Markbåge "Make it work for the 90%. Document the 10%. Ignore the 1%." — React team on API design

角色定义

此 Skill 激活后,你写出的代码应该让 React 核心 contributor 在 code review 时感觉 「这代码是从 react-reconciler 里长出来的」,而不是「这是一个不了解 Fiber 的人写的」。

这意味着:Fiber 思维优先、effects 显式分层、调度器感知、Flow/TypeScript 类型驱动。


命名 DNA

6 条直觉规则:

  1. Fiber 节点相关变量用 fiber、current、workInProgress(不缩写)

    js
    // ✅ 语义清晰,和 Fiber 架构术语对齐
    function updateFunctionComponent(current, workInProgress, Component, nextProps) {
      const nextChildren = renderWithHooks(current, workInProgress, Component, nextProps);
      reconcileChildren(current, workInProgress, nextChildren);
      return workInProgress.child;
    }
    
    // ❌ 缩写丢失上下文
    function updateFnComp(cur, wip, comp, props) { ... }
  2. effect 标志位用全大写常量 + 位运算,命名以 Flags 结尾

    js
    // ✅ packages/react-reconciler/src/ReactFiberFlags.js 风格
    export const NoFlags        = /*                      */ 0b000000000000000000000000000;
    export const PerformedWork  = /*                      */ 0b000000000000000000000000001;
    export const Placement      = /*                      */ 0b000000000000000000000000010;
    export const Update         = /*                      */ 0b000000000000000000000000100;
    export const Deletion       = /*                      */ 0b000000000000000000001000000;
    export const ChildDeletion  = /*                      */ 0b000000000000000000010000000;
    
    // ❌ 字符串枚举或对象映射(性能差、位操作不方便)
    const EFFECT_TYPE = { PLACEMENT: 'placement', UPDATE: 'update' };
  3. phase 函数命名:begin / complete / commit 三段式

    js
    // ✅ 和 Fiber 工作循环的三阶段对齐
    function beginWork(current, workInProgress, renderLanes) { ... }
    function completeWork(current, workInProgress, renderLanes) { ... }
    function commitMutationEffects(root, finishedWork, committedLanes) { ... }
    
    // ❌ 语义模糊的动词
    function processNode(fiber) { ... }
    function handleWork(fiber) { ... }
  4. lanes(优先级)相关变量总是带 Lanes 或 Lane 后缀

    js
    // ✅
    const renderLanes: Lanes = NoLanes;
    const updateLane: Lane = requestUpdateLane(fiber);
    function mergeLanes(a: Lanes, b: Lanes): Lanes { return a | b; }
    function isSubsetOfLanes(set: Lanes, subset: Lanes): boolean { return (set & subset) === subset; }
    
    // ❌ 裸数字或模糊命名
    const priority = 0;
    const urgency = requestPriority();
  5. Hook 链表节点:hook、workInProgressHook、currentHook(不叫 node)

    js
    // ✅ packages/react-reconciler/src/ReactFiberHooks.js 风格
    let workInProgressHook: Hook | null = null;
    let currentHook: Hook | null = null;
    
    function updateWorkInProgressHook(): Hook {
      let nextCurrentHook: null | Hook;
      if (currentHook === null) {
        const current = currentlyRenderingFiber.alternate;
        nextCurrentHook = current !== null ? current.memoizedState : null;
      } else {
        nextCurrentHook = currentHook.next;
      }
      // ...
    }
  6. is 前缀用于布尔判断函数,has 前缀用于存在性检查

    js
    // ✅
    function isRootDehydrated(root: FiberRoot): boolean { ... }
    function hasContextChanged(): boolean { ... }
    function isFiberMounted(fiber: Fiber): boolean { ... }
    
    // ❌
    function checkRootDehydrated(root) { ... }
    function contextChanged() { ... }

结构偏好

Fiber 工作循环的三阶段严格分离,不能跨界:

js
// ✅ render phase(可中断、可重复)— 只读 current,只写 workInProgress
function performUnitOfWork(unitOfWork: Fiber): void {
  const current = unitOfWork.alternate;
  let next = beginWork(current, unitOfWork, renderLanes);
  unitOfWork.memoizedProps = unitOfWork.pendingProps;
  if (next === null) {
    completeUnitOfWork(unitOfWork);  // 向上回溯
  } else {
    workInProgress = next;  // 向下深入
  }
}

// ✅ commit phase(同步、不可中断)— 操作真实 DOM、调用 effects
function commitRoot(root: FiberRoot, finishedWork: Fiber, lanes: Lanes): void {
  // 三趟 commit:BeforeMutation → Mutation → Layout
  commitBeforeMutationEffects(root, finishedWork);
  commitMutationEffects(root, finishedWork, lanes);
  root.current = finishedWork;  // 切换 current 树(只在这里!)
  commitLayoutEffects(finishedWork, root, lanes);
}

// ❌ 在 render phase 操作 DOM(破坏 concurrent mode)
function beginWork(current, workInProgress) {
  document.getElementById('app').style.display = 'none';  // 绝对不行
}

Effects 链表:收集在 render phase,执行在 commit phase

js
// ✅ render phase 只 mark flags,不执行
function markUpdate(workInProgress: Fiber): void {
  workInProgress.flags |= Update;
}

// ✅ commit phase 遍历 subtreeFlags 剪枝优化
function commitMutationEffectsOnFiber(finishedWork: Fiber, root: FiberRoot) {
  const flags = finishedWork.flags;

  switch (finishedWork.tag) {
    case FunctionComponent: {
      if (flags & Update) {
        commitHookEffectListUnmount(HookLayout | HookHasEffect, finishedWork, finishedWork.return);
      }
      break;
    }
    // ...
  }
}

模块组织:按 Fiber tag(组件类型)而非功能分文件

react-reconciler/src/
├── ReactFiber.js           # Fiber 节点创建
├── ReactFiberBeginWork.js  # render phase 向下(按 tag switch)
├── ReactFiberCompleteWork.js # render phase 向上(按 tag switch)
├── ReactFiberCommitWork.js # commit phase(三趟 pass)
├── ReactFiberHooks.js      # Function Component Hooks
├── ReactFiberFlags.js      # effect 标志位常量
├── ReactFiberLane.js       # 优先级 lanes 系统
└── ReactFiberScheduler.js  # 与 scheduler 包交互

与 Scheduler 的交互:永远通过回调,不直接调用 Scheduler 内部 API

js
// ✅ 通过 scheduleCallback 注册工作单元
function ensureRootIsScheduled(root: FiberRoot, currentTime: number): void {
  const nextLanes = getNextLanes(root, root === workInProgressRoot ? workInProgressRootRenderLanes : NoLanes);
  const newCallbackPriority = getHighestPriorityLane(nextLanes);

  // 用 Scheduler 优先级调度
  let schedulerPriorityLevel: PriorityLevel;
  switch (lanesToEventPriority(nextLanes)) {
    case DiscreteEventPriority:
      schedulerPriorityLevel = ImmediateSchedulerPriority;
      break;
    case ContinuousEventPriority:
      schedulerPriorityLevel = UserBlockingSchedulerPriority;
      break;
    default:
      schedulerPriorityLevel = NormalSchedulerPriority;
  }

  newCallbackNode = scheduleCallback(
    schedulerPriorityLevel,
    performConcurrentWorkOnRoot.bind(null, root),
  );
}

// ❌ 直接操作 Scheduler 内部队列(跨包越界)
import { taskQueue } from 'scheduler/src/SchedulerMinHeap';
taskQueue.push(myTask);

Flow/TypeScript 类型注释习惯:

js
// ✅ Fiber 节点类型用 opaque type(Flow)或接口(TS)
// Flow 风格(React 内部使用 Flow)
opaque type Lane: number = number;
opaque type Lanes: number = number;

// ✅ 复杂类型单独定义,不内联
type Effect = {
  tag: HookFlags,
  create: () => (() => void) | void,
  destroy: (() => void) | void,
  deps: Array<mixed> | void | null,
  next: Effect,
};

// ✅ 函数签名完整标注,返回类型不省略
function createFiber(
  tag: WorkTag,
  pendingProps: mixed,
  key: null | string,
  mode: TypeOfMode,
): Fiber { ... }

注释哲学

注释解释"为什么",不解释"是什么":

js
// ✅ 解释 Fiber 双缓冲的设计意图
// We use a double buffering pooling technique because we need to be able to
// free extra fibers without doing extra GC scrutiny. The trick is, if the
// alternate has no more work, it can be reused without allocating a new object.
// However, since there's only at most two versions of each fiber in our tree,
// we want to make sure that we're not reusing the same fibers for different
// two different work in progress.

// ✅ 解释边界条件和 hack
// This is a work around for the warning case where we call a callback during
// commit phase to trigger an update but then don't flush that update on the
// same tick. The commit phase will then unmount the component and the
// suspense boundary will not be triggered again.
// TODO: We should probably just always flush synchronously in that case.
if (enableSchedulingProfiler) {
  markStateUpdateScheduled(fiber, lane);
}

// ❌ 复述代码的废话注释
// Merge the lanes
const mergedLanes = mergeLanes(laneA, laneB);

// ❌ 没有 TODO 格式的临时代码
// fix this later
// hackfix for safari

TODO/FIXME 格式规范:

js
// TODO: Consider using WeakMap for this to avoid memory leaks.
// FIXME: This is O(n²) and needs to be optimized before v19.
// NOTE: This intentionally does not check for Strict Mode because...
// HACK: Temporarily work around a Safari bug (webkit.org/b/12345)

反模式(绝不这样写)

  1. 在 render phase 产生副作用

    js
    // ❌ render 是纯函数阶段,不能有副作用
    function beginWork(current, workInProgress) {
      fetch('/api/data').then(setGlobalCache);  // 会在中断后重复执行!
      analytics.track('component_rendered');
      return null;
    }
    // ✅ 副作用放进 commitWork 或 useEffect
  2. 直接修改 current Fiber(render phase 只能写 workInProgress)

    js
    // ❌ 破坏双缓冲机制
    function updateState(current, workInProgress) {
      current.memoizedState = newState;  // 绝对不行!
    }
    // ✅
    workInProgress.memoizedState = newState;
  3. root.current 在 commit 中途切换

    js
    // ❌ 必须在 mutation pass 之后、layout pass 之前切换
    function commitRoot(root, finishedWork) {
      root.current = finishedWork;  // 时机错误
      commitMutationEffects(root, finishedWork);  // DOM 操作时 current 已经是新树
    }
    // ✅ 严格按 BeforeMutation → Mutation → 切换 current → Layout 顺序
  4. lane 优先级硬编码数字

    js
    // ❌ 魔法数字无法维护
    if (fiber.lanes & 1) { ... }
    if (priority === 2) { ... }
    // ✅ 用常量
    if (includesSomeLane(fiber.lanes, SyncLane)) { ... }
    if (lane === InputContinuousLane) { ... }
  5. 跨包直接 import 内部模块

    js
    // ❌ 破坏包边界(react-dom 不应该直接 import reconciler 内部)
    import { workInProgress } from 'react-reconciler/src/ReactFiberWorkLoop';
    // ✅ 通过 reconciler 公开的 HostConfig 接口交互
  6. 用 any 类型逃逸(Flow 里的 mixed 也要谨慎)

    js
    // ❌ 类型系统保护 Fiber 不变量,any 会掩盖 bug
    function updateFiber(fiber: any) { ... }
    // ✅
    function updateFiber(fiber: Fiber) { ... }
  7. Hooks 在条件语句里调用(连内部实现也要保持 hook 链表顺序)

    js
    // ❌ 打破 hook 链表的索引假设
    function renderWithHooks(current, workInProgress, Component) {
      if (someCondition) {
        useState(null);  // 链表位置不稳定!
      }
    }
  8. __DEV__ 检查不完整

    js
    // ❌ 生产包里不应该有调试字符串
    throw new Error('Something went wrong in ' + componentName);
    // ✅
    if (__DEV__) {
      throw new Error(`Something went wrong in "${getComponentNameFromFiber(fiber)}"`);
    } else {
      throw new Error('Something went wrong.');
    }

校验测试

  1. 双缓冲检查:你有没有在 render phase 写 current.xxx = ...?只能写 workInProgress.xxx。
  2. 副作用分层:DOM 操作、ref 更新、useEffect 调用,有没有放在 commit phase?render phase 必须是纯的。
  3. lanes 可读性:优先级相关的变量有没有用常量(SyncLane、DefaultLane)而不是裸数字?

来源

Heefeg gestallte Froen

Wat mécht de KI-Skill React Style?

React 核心源码编码风格 Skill。蒸馏自 facebook/react 核心包(packages/react-dom、 packages/react-reconciler、packages/scheduler),以及 Dan Abramov、Sebastian Markbåge、 Andrew Clark 的 PR review 和设计文档。 触发词:「React 源码风格」「Fiber 架构」「reconciler 风格」「react core style」「React 内部实现」。 适用:React 核心贡献、自定义 reconciler、调度器集成、Fiber 树遍历、effects 系统开发。

Firwat React Style op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. React Style besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech React Style an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/happydog-intj/luban-skill/tree/master/skills/react.skill an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen React Style benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat React Style benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir React Style domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill React Style gratis?

De Skill gëtt vum happydog-intj op GitHub publizéiert. Kuckt am Repository no de Lizenzbedéngungen. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇