import { useEffect, useRef } from 'react';

/**
 * 当指定的条件为真时执行 Effect 函数。
 *
 * @param effect - The effect function to execute.
 * @param when - The condition to trigger the effect.
 * @param deps - The dependencies for the effect.
 */
export const useEffectWhen = (effect: () => void, when: boolean, deps: React.DependencyList) => {
  const requestFn = useRef<(() => void) | undefined>(effect);
  useEffect(() => {
    requestFn.current = effect;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [...deps, effect]);

  useEffect(() => {
    if (when && requestFn.current) {
      requestFn.current();
      requestFn.current = undefined;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [...deps, when]);
};
