import React, {
  DependencyList,
  EffectCallback,
  useEffect,
  useRef,
} from "react";

/**
 * React.useEffect, except that it never runs on mount.
 * This is emulating the componentDidUpdate lifecycle function.
 */
export const useEffectExceptOnMount = (
  effect: EffectCallback,
  dependencies?: DependencyList
): void => {
  const mounted = useRef(false);
  useEffect(() => {
    if (mounted.current) {
      const unmount = effect();
      return () => unmount && unmount();
    } else {
      mounted.current = true;
    }
  }, dependencies);

  //Reset on unmount for the next mount.
  useEffect(() => {
    return () => {
      mounted.current = false;
    };
  }, []);
};
