import React, { DependencyList, useEffect, useLayoutEffect, useRef } from 'react';
import { dequal as deepEqual } from 'dequal';

function useDeepCompareMemoize(value: DependencyList): any {
   const ref = React.useRef<DependencyList>();
   const signalRef = React.useRef<boolean>(false);

   if (!deepEqual(value, ref.current)) {
      ref.current = value;
      signalRef.current = !signalRef.current;
   }

   return [signalRef.current];
}

/**
 * useDeepCompareEffect com useLayoutEffect ignorando o primeiro valor
 * @param effect
 * @param deps
 */
export const useDidUpdateDeepCompareLayoutEffect: typeof useEffect = function useDidUpdateDeepCompareEffect(
   effect,
   deps?,
): any {
   const didMountRef = useRef(false);

   useLayoutEffect(() => {
      if (didMountRef.current) effect();
      else didMountRef.current = true;
   }, useDeepCompareMemoize(deps));
};
