useState源码解读 及 手撕 useState 实现
创始人
2024-03-20 03:09:17

文章目录

  • useState源码解读 及 手撕 useState 实现
    • useState源码分析
      • 逻辑图
      • 源码解读
        • mountState
          • mountWorkInProgressHook 函数
        • updateState
          • updateReducer 函数
    • 实现
    • 对比图
    • 实现效果
      • 只声明一个 hook
      • 重复调用同一个 hook
      • 声明多个不同的 hooks
    • 体验收获

useState源码解读 及 手撕 useState 实现

useState源码分析

逻辑图

在这里插入图片描述

源码解读

hooks 保存在 packages/react-reconciler/src/ReactFiberHooks.old.js 文件中

有一个 dispatcher 的数据结构,是个对象,在不同的 dispatcher 中,都同样存在了 useState;

在不同的 dispatcher 中,useState 的实现对应的是不同的方法:

即 useState 在不同的上下文中对应的是不同的函数
所以:react 通过在不同的上下文使用不同的 dispatcher,来区分当前需要使用 hooks 的不同实现

比如:
在这里插入图片描述

mountState

首先看 mountState 的实现:

  1. 调用 mountWorkInProgressHook 创建hook对象
  2. 初始化 memoizedState 和 baseState ,值为 initialState
  3. 创建 hook 的 updateQueue
  4. 创建 dispatch 方法(其实就是 绑定了当前的 fiber和 queue 的 dispatchAction )

在这里插入图片描述

mountWorkInProgressHook 函数
  1. 创建一个 hook 对象
  2. 若这是第一个 hook,挂载到 memoizedState
  3. 若不是第一个hook的话,就会把他挂载到上一个 hook的 next 指针下,与上一个hook形成一条链表
  4. 返回 该hook 对象

在这里插入图片描述

updateState

在这里插入图片描述

其实,useState 就是一个预置了 reducer 的 useReducer,预置的 reducer 就是 basicStateReducer

在这里插入图片描述

updateReducer 函数

总结:首先获取当前 hooks和 当前的 queue,之后就会 根据 baseState 和 拥有优先级 的 update来计算 memoizedState

具体代码在这:

function updateReducer(reducer: (S, A) => S,initialArg: I,init?: I => S,
): [S, Dispatch] {const hook = updateWorkInProgressHook();const queue = hook.queue;invariant(queue !== null,'Should have a queue. This is likely a bug in React. Please file an issue.',);queue.lastRenderedReducer = reducer;const current: Hook = (currentHook: any);// The last rebase update that is NOT part of the base state.let baseQueue = current.baseQueue;// The last pending update that hasn't been processed yet.const pendingQueue = queue.pending;if (pendingQueue !== null) {// We have new updates that haven't been processed yet.// We'll add them to the base queue.if (baseQueue !== null) {// Merge the pending queue and the base queue.const baseFirst = baseQueue.next;const pendingFirst = pendingQueue.next;baseQueue.next = pendingFirst;pendingQueue.next = baseFirst;}if (__DEV__) {if (current.baseQueue !== baseQueue) {// Internal invariant that should never happen, but feasibly could in// the future if we implement resuming, or some form of that.console.error('Internal error: Expected work-in-progress queue to be a clone. ' +'This is a bug in React.',);}}current.baseQueue = baseQueue = pendingQueue;queue.pending = null;}if (baseQueue !== null) {// We have a queue to process.const first = baseQueue.next;let newState = current.baseState;let newBaseState = null;let newBaseQueueFirst = null;let newBaseQueueLast = null;let update = first;do {const updateLane = update.lane;if (!isSubsetOfLanes(renderLanes, updateLane)) {// Priority is insufficient. Skip this update. If this is the first// skipped update, the previous update/state is the new base// update/state.const clone: Update = {lane: updateLane,action: update.action,eagerReducer: update.eagerReducer,eagerState: update.eagerState,next: (null: any),};if (newBaseQueueLast === null) {newBaseQueueFirst = newBaseQueueLast = clone;newBaseState = newState;} else {newBaseQueueLast = newBaseQueueLast.next = clone;}// Update the remaining priority in the queue.// TODO: Don't need to accumulate this. Instead, we can remove// renderLanes from the original lanes.currentlyRenderingFiber.lanes = mergeLanes(currentlyRenderingFiber.lanes,updateLane,);markSkippedUpdateLanes(updateLane);} else {// This update does have sufficient priority.if (newBaseQueueLast !== null) {const clone: Update = {// This update is going to be committed so we never want uncommit// it. Using NoLane works because 0 is a subset of all bitmasks, so// this will never be skipped by the check above.lane: NoLane,action: update.action,eagerReducer: update.eagerReducer,eagerState: update.eagerState,next: (null: any),};newBaseQueueLast = newBaseQueueLast.next = clone;}// Process this update.if (update.eagerReducer === reducer) {// If this update was processed eagerly, and its reducer matches the// current reducer, we can use the eagerly computed state.newState = ((update.eagerState: any): S);} else {const action = update.action;newState = reducer(newState, action);}}update = update.next;} while (update !== null && update !== first);if (newBaseQueueLast === null) {newBaseState = newState;} else {newBaseQueueLast.next = (newBaseQueueFirst: any);}// Mark that the fiber performed work, but only if the new state is// different from the current state.if (!is(newState, hook.memoizedState)) {markWorkInProgressReceivedUpdate();}hook.memoizedState = newState;hook.baseState = newBaseState;hook.baseQueue = newBaseQueueLast;queue.lastRenderedState = newState;}const dispatch: Dispatch = (queue.dispatch: any);return [hook.memoizedState, dispatch];
}

查阅各种文档资料视频等,勉勉强强的弄懂了 useState 的实现原理,今天来简单实现一下 useState,思路都在 代码注释中:

实现


Document


对比图

在这里插入图片描述

在这里插入图片描述

实现效果

只声明一个 hook

在这里插入图片描述

在这里插入图片描述

重复调用同一个 hook

在这里插入图片描述

在这里插入图片描述

声明多个不同的 hooks

在这里插入图片描述

在这里插入图片描述

体验收获

源码确实很难,需要花很多时间,但是弄懂了之后,很有成就感,也觉得 react 没有那么神秘了,加油!

相关内容

热门资讯

最新或2023(历届)武汉纺织... 武汉纺织大学外经贸学院,是2003年经国家教育部批准设立的一所工、文、经、管、艺相结合、相互渗透的本...
最新或2023(历届)武汉工程... 武汉工程大学邮电与信息工程学院是国家教育部首批确认具有普通高等教育办学资格的独立学院。学院创建于20...
最新或2023(历届)中原工学... 中原工学院信息商务学院成立于2003年4月,是首批经国家教育部批准具有全日制普通本科学历教育办学资格...
最新或2023(历届)河南理工... 河南理工大学万方科技学院创建于2002年,是经教育部批准设立的河南省第一所独立学院,办学层次为全日制...
最新或2023(历届)河南科技... 河南科技学院新科学院地处中原名城新乡市,是教育部批准的按新机制、新模式举办的独立学院,属于本科层次学...