import { DependencyList, useState } from 'react';
import useDeepCompareEffect from 'use-deep-compare-effect';
import { useDidUpdateDeepCompareEffect } from '../useDidUpdateDeepCompareEffect';

export function useMemoImmer<T>(factory: () => T, deps: DependencyList | undefined): T {
   const [memo, setMemo] = useState<T>(factory());

   checkDeps(deps);

   useDidUpdateDeepCompareEffect(() => {
      setMemo(factory());
   }, deps);

   return memo;
}

function checkDeps(deps): void {
   if (!deps || !deps.length) {
      throw new Error('useMemoImmer should not be used with no dependencies. Use React.useEffect instead.');
   }
}
