Skip to content

Instantly share code, notes, and snippets.

@sepeth
Last active September 23, 2020 08:06
Show Gist options
  • Save sepeth/d95593666868c46890899f88c02aeb67 to your computer and use it in GitHub Desktop.
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.
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