import _ from 'lodash';
import { useEffect, useState } from 'react';

/**
 * This hook automatically memoizes an object using its value's equality check as a discrimination criterion.
 * PLEASE NOTE!!! The equality check of a JS object is an extremely complex issue.
 * Therefore, this hook should be used with extreme caution, only when strictly necessary and only if you fully master the topic above and its implications in the conditional rendering logic of React
 */
function useMemoizedObject<T extends object>(object: T): T {
  if (!_.isPlainObject(object)) {
    throw new Error('[useMemoizedObject]: param must be a plain JS object');
  }

  const [memoObj, setMemoObj] = useState(object);

  useEffect(() => {
    if (!_.isEqual(object, memoObj)) {
      setMemoObj(object);
    }
  }, [object, memoObj]);

  return memoObj;
}

export { useMemoizedObject };
