import { useEffect, useMemo, useRef } from "react";

type Destructor = (() => void) | undefined | void;
type DependencyList = readonly unknown[];

export const useSyncEffect = (effect: () => Destructor, deps: DependencyList) => {
  const destructorRef = useRef<Destructor>();

  const cleanUp = () => {
    const destructor = destructorRef.current;
    if (destructor) {
      destructor();
    }
  };

  useMemo(() => {
    cleanUp();
    destructorRef.current = effect();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  useEffect(() => {
    return cleanUp;
  }, []);
};
