Created
June 23, 2020 17:25
-
-
Save jtmthf/61068c99cc5d3e5c90c43198608c92e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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