React 实现 useState

本文将带大家实现 useState。

先看下如何使用。

js 复制代码
function FunctionComponent() {
  const [count1, setCount1] = useState(1);

  return (
    <div className="border">
      <button
        onClick={() => {
          setCount1(count1 + 1);
        }}
      >
        {count1}
      </button>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  (<FunctionComponent />) as any
);

useState 是基于 useReducer 实现的,参考文章 React 实现 useReducer

实现 useState

js 复制代码
// 源码中 useState 与 useReducer 对比:
// useState 如果 state 没有改变,不引起组件更新。useReducer 不是如此。(老的源码中,state 没有改变,两者都不更新)
// reducer 代表 state 修改规则,useReducer 比较方便复用这个规则
export function useState<S>(initialState: (() => S) | S) {
  const init = isFn(initialState) ? (initialState as any)() : initialState;
  return useReducer(null, init);
}

useReducer 修改

为了适配 useStateuseReducerdispatchReducerAction 两个函数的 reducer 参数增加了 null。

js 复制代码
export function useReducer<S, I, A>(
  reducer: ((state: S, action: A) => S) | null,
  initialArg: I,
  init?: (initialArg: I) => S
) {
    ...
}

function dispatchReducerAction<S, I, A>(
  fiber: Fiber,
  hook: Hook,
  reducer: ((state: S, action: A) => S) | null,
  action: any
) {
    ...
}

再聊 scheduleUpdateOnFiber

Fiber hooks 调用 scheduleUpdateOnFiber 时,第三个参数传的都是 true。

因为 React 考虑到 ensureRootIsScheduled 使用到了调度器,会增加复杂度。

js 复制代码
export function scheduleUpdateOnFiber(
  root: FiberRoot,
  fiber: Fiber,
  isSync?: boolean
) {
  workInProgressRoot = root;
  workInProgress = fiber;

  if (isSync) {
    // queueMicrotask 是 JS 原生 API
    queueMicrotask(() => performConcurrentWorkOnRoot(root));
  } else {
    ensureRootIsScheduled(root);
  }
}

export function performConcurrentWorkOnRoot(root: FiberRoot) {
  // 1. render, 构建 fiber 树,即 VDOM(beginWork|completeWork)
  renderRootSync(root);

  const finishedWork = root.current.alternate;
  root.finishedWork = finishedWork; // 根 Fiber

  // 2. commit, VDOM -> DOM
  commitRoot(root);
}
相关推荐
倔强的石头10623 分钟前
【Linux指南】动静态库系列(七):符号表与重定位:链接器如何把函数调用接起来
linux·前端·javascript
a1117762 小时前
3D 脑图谱 / Bilingual 3D Brain Atlas 项目
前端
T1mzhou2 小时前
ARM64 Linux 6.10内核启动流程2-rootfs 怎么挂上
linux·服务器·前端
小小尚@2 小时前
WebGIS/ECharts 地图开发|MapLand 在线行政区划边界一键下载 GeoJSON 工具
前端·javascript·echarts
默_笙3 小时前
🚍 一条 Todo 的奇幻漂流:TypeScript 全栈类型安全的"护照检查"
前端·javascript
计算机魔术师4 小时前
NVIDIA 以 129.3 亿美元收购 Hugging Face
前端
平头哥技术团队4 小时前
Day 01 | 用 HTML 写第一个网页:双击就能在浏览器打开
前端
计算机魔术师5 小时前
两年翻45倍!英伟达靠买买买建成千亿投资帝国
前端
paopaokaka_luck5 小时前
基于springboot3+vue3的精准扶贫管理系统(AI 问答、ECharts 图形化分析)
前端·人工智能·echarts
l1m0_5 小时前
智能电动自行车管理后台实战:AI生成页面与React组件化技巧
前端·react.js·ui·ai·设计