Open2

Reactで連打を防止するフック

Nakano as a ServiceNakano as a Service
import { useCallback, useRef } from 'react';

function useExclusiveFn<U extends Promise<unknown>>(callback: () => U) {
  const promiseRef = useRef<U | null>(null);

  return useCallback(() => {
    if (promiseRef.current) {
      return promiseRef.current;
    }

    const promise = callback();
    promiseRef.current = promise;

    promise.finally(() => {
      promiseRef.current = null;
    });

    return promise;
  }, [callback]);
}
Nakano as a ServiceNakano as a Service

依存配列を外から渡す場合とどちらがいいのだろうか、、、

import { DependencyList, useCallback, useRef } from 'react';

function useExclusiveFn<U extends Promise<unknown>>(
  callback: () => U,
  deps: DependencyList
) {
  const promiseRef = useRef<U | null>(null);

  return useCallback(() => {
    if (promiseRef.current) {
      return promiseRef.current;
    }

    const promise = callback();
    promiseRef.current = promise;

    promise.finally(() => {
      promiseRef.current = null;
    });

    return promise;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);
}