Last active
September 23, 2020 08:06
-
-
Save sepeth/d95593666868c46890899f88c02aeb67 to your computer and use it in GitHub Desktop.
Gives you a func that you can call once. It is for React.
This file contains 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 {DependencyList, useCallback, useRef} from "react"; | |
interface AnyFn<ReturnType> { | |
(...args: any[]): ReturnType; | |
} | |
/** Gives you a func that you can call once. | |
* | |
* It will store the return value of the original call, and return that for subsequent calls. | |
* This is true even when the deps change. | |
*/ | |
export function useCallbackOnce<RT>(cb: AnyFn<RT>, deps: DependencyList): AnyFn<RT> { | |
let isCalled = useRef(false); | |
let content = useRef<RT>(); | |
return useCallback( | |
((...args: any[]) => { | |
if (!isCalled.current) { | |
isCalled.current = true; | |
content.current = cb(...args); | |
} | |
return content.current; | |
}) as AnyFn<RT>, | |
deps | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment