极简 useState:手写 20 行,支持多次 setState 合并

180 阅读1分钟

不依赖 React,用 闭包 + 批处理队列 实现可合并更新的 useState


一、20 行完整代码

function createUseState(initialValue) {
  let state = initialValue;
  let pending = null;              // 合并队列
  let listeners = [];

  const flush = () => {
    if (pending !== null) {
      state = pending(state);
      pending = null;
      listeners.forEach(fn => fn(state));
    }
  };

  const useState = (value) => {
    if (arguments.length) state = value; // 初始化
    return [
      state,
      (updater) => {
        // 合并更新:函数或值
        pending = typeof updater === 'function'
          ? (prev) => updater(prev)
          : () => updater;
        Promise.resolve().then(flush); // 微任务批处理
      }
    ];
  };

  useState.subscribe = (fn) => listeners.push(fn);

  return useState;
}

二、使用示例

const [count, setCount] = createUseState(0);

setCount(c => c + 1);
setCount(c => c + 2); // 合并执行,state 变为 3
console.log(count);   // 3

三、一句话总结

20 行闭包 + 微任务批处理,让多次 setState 合并为一次更新。