[react-hooks]|[react-hooks] 利用useReducer实现useState

useState 和 useReducer 是使 FunctionComponent 获得状态的2个hooks函数,我在初期的时候以为它们是2个完全不相干(各自独立)的两个函数实现,可是在逐步深入了解hooks的过程中我发现并不是这样,如果又跟我一样想法同学记得给该篇文章点个赞。
官方对 useReducer 的定位

`useReducer` is usually preferable to `useState` when you have complex state logic that involves multiple sub-values. It also lets you optimize performance for components that trigger deep updates because you can pass `dispatch` down instead of callbacks.

对于一个复杂逻辑且有嵌套的状态来说,useReducer能带来渲染性能的提升,毕竟一个action是会触发兄弟结点的更新的,这对于用useState来实现是比较繁琐的
初衷
记得某篇博客还是某面试集的题有表述,useState本身就是用useReducer实现的,意味着useState是useReducer的一个扩展子集,且今天刚好对比了下 types文件,如下
function useState(initialState: S | (()=>S)): [S,(value:S | ((prev:S)=>void))=>void]function useReducer( reducer: R, initializerArg: I, initializer: (arg: I) => ReducerStateWithoutAction ): [ReducerStateWithoutAction, DispatchWithoutAction];

【[react-hooks]|[react-hooks] 利用useReducer实现useState】从这里我们可以看出来useState用useReducer来实现的可行性
function useState(initialState: T | (() => T)) { const initState: T = // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore typeof initialState === 'function' ? initialState() : initialState; const [state, dispatch] = React.useReducer( // eslint-disable-next-line no-shadow (state: T, action: T | ((prev: T) => T)) => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore return typeof action === 'function' ? action(state) : action; }, initState, ); return [ state, (value: T | ((prev: T) => T)) => { if (value !== state) { dispatch(value); } }, ]; }

    推荐阅读