index.ts 807 B

12345678910111213141516171819202122232425262728293031323334
  1. import {deepEqual} from '@utils';
  2. import {useLatest} from 'ahooks';
  3. import {useMemo} from 'react';
  4. import {useContextSelector, Context} from 'use-context-selector';
  5. const selectorFn = <T>(state: T) => state ;
  6. export function useContextSection<T, R>(
  7. context: Context<T>,
  8. selector: (state: T) => R,
  9. ) {
  10. const f = useLatest(selector);
  11. const callback = useMemo(
  12. function() {
  13. let memoState: R | null = null;
  14. return function(state: T) {
  15. const newState = f.current(state);
  16. if (!memoState || !deepEqual(memoState, newState)) return (memoState = newState);
  17. return memoState;
  18. };
  19. },
  20. [f],
  21. );
  22. return useContextSelector(context, callback);
  23. }
  24. export function useContext<T>(context: Context<T>) {
  25. return useContextSection(context, selectorFn);
  26. }