js实现reacthooks
React Hooks 实现原理(JavaScript 版本)
React Hooks 的核心是通过闭包和链表管理组件的状态与生命周期。以下是关键实现思路:
基础 Hook 实现
let currentComponent = null;
let hookIndex = 0;
let hooks = [];
function useState(initialValue) {
const _hookIndex = hookIndex;
if (!hooks[_hookIndex]) {
hooks[_hookIndex] = {
state: typeof initialValue === 'function'
? initialValue()
: initialValue
};
}
const setState = (newValue) => {
hooks[_hookIndex].state = newValue;
render(); // 触发重新渲染
};
hookIndex++;
return [hooks[_hookIndex].state, setState];
}
组件执行流程控制
function renderComponent(component) {
currentComponent = component;
hookIndex = 0;
return component();
}
function render() {
// 实际React会进行VDOM比对
renderComponent(currentComponent);
}
useEffect 实现

function useEffect(callback, deps) {
const _hookIndex = hookIndex;
const hasNoDeps = !deps;
const oldDeps = hooks[_hookIndex]?.deps;
const hasChangedDeps = oldDeps
? !deps.every((dep, i) => dep === oldDeps[i])
: true;
if (hasNoDeps || hasChangedDeps) {
setTimeout(callback); // 简化的异步执行
hooks[_hookIndex] = { deps };
}
hookIndex++;
}
使用示例
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count updated: ${count}`);
}, [count]);
return {
click: () => setCount(count + 1),
render: () => console.log(`Current count: ${count}`)
};
}
const app = renderComponent(Counter);
app.click(); // 触发更新
app.render();
关键实现细节
-
闭包存储状态
Hooks 通过闭包保存当前组件的状态和索引,确保每次渲染都能正确访问对应的 hook 数据。
-
调用顺序保证
hookIndex在每次渲染时重置,严格保证 hooks 的调用顺序与数量一致。 -
依赖数组比对
useEffect通过浅比较依赖数组决定是否执行副作用。 -
批量更新优化
实际 React 会合并多个状态更新,上述简化版直接触发渲染。
完整实现注意事项
- 需要实现调度器控制渲染时机
- 需要处理组件卸载时的清理工作
- 需要实现 useMemo/useCallback 等性能优化 Hook
- 需要处理并发模式下的状态更新
这种实现方式展示了 React Hooks 的核心思想,实际 React 代码库包含更多边界情况处理和性能优化。






