Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created June 23, 2020 17:25
Show Gist options
  • Select an option

  • Save jtmthf/61068c99cc5d3e5c90c43198608c92e4 to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/61068c99cc5d3e5c90c43198608c92e4 to your computer and use it in GitHub Desktop.
import { useRef, useCallback, DependencyList } from 'react';
function useBlockingCallback<T extends (...args: any[]) => any>(
callback: T,
initiallyBlocked = false,
deps: DependencyList = [],
): [T, (blocked?: boolean) => void] {
const blockRef = useRef(initiallyBlocked);
const handler = useCallback(
((...args) => {
if (!blockRef.current) {
callback(...args);
}
}) as T,
[deps],
);
const setBlocked = useCallback((blocked = true) => {
blockRef.current = blocked;
}, []);
return [handler, setBlocked];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment