import {deepEqual} from '@utils';
import {useLatest} from 'ahooks';
import {useMemo} from 'react';
import {useContextSelector, Context} from 'use-context-selector';

const selectorFn = <T>(state: T) => state ;

export function useContextSection<T, R>(
  context: Context<T>,
  selector: (state: T) => R,
) {
  const f = useLatest(selector);

  const callback = useMemo(
    function() {
      let memoState: R | null = null;

      return function(state: T) {
        const newState = f.current(state);

        if (!memoState || !deepEqual(memoState, newState)) return (memoState = newState);

        return memoState;
      };
    },
    [f],
  );

  return useContextSelector(context, callback);
}

export function useContext<T>(context: Context<T>) {
  return useContextSection(context, selectorFn);
}
