React自定义hook 给异步函数增加竞态锁,防止并发执行。

useLockCallback 和 useCallback用法一致,使用ref标记防止并发执行

import { useCallback, useRef } from 'react';

export default function useLockCallback any>(callback: T, deps: DependencyList) {
  const lock = useRef(false);
  return useCallback(async (...args) => {
    if (lock.current) return;
    lock.current = true;
    try {
      const req = await callback(...args);
      lock.current = false;
      return req;
    } catch (e) {
      lock.current = false;
      throw e;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);
}

你可能感兴趣的:(React自定义hook 给异步函数增加竞态锁,防止并发执行。)