深入理解 React Hooks:从原理到实践
前言
React Hooks 自 16.8 版本引入以来,彻底改变了 React 组件的编写方式。
useState 的底层实现
function useState<T>(initialState: T): [T, (newState: T) => void] {
const hook = getCurrentHook();
if (!hook.initialized) {
hook.state = initialState;
hook.initialized = true;
}
const setState = (newState: T) => {
hook.state = newState;
scheduleRender();
};
return [hook.state, setState];
}