Last active
April 4, 2024 04:44
-
-
Save huynhducduy/03790a82e390413a649db7c6ec160547 to your computer and use it in GitHub Desktop.
useBetterCallback (with type-safe, make sure props and arguments passed always be memoized callbacks)
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 {useCallback as useCallbackBase} from 'react' | |
/* | |
* Use this type to make sure that the callback passed will always be a memoized callback | |
*/ | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export interface MemoizedCallback<T extends (...args: any[]) => any> { | |
(...args: Parameters<T>): ReturnType<T> | |
memoized: true | |
} | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
function memoizeCallback<T extends (...args: any[]) => any>(callback: T) { | |
// @ts-expect-error Escape typescript | |
callback.memoized = true | |
return callback as unknown as MemoizedCallback<T> | |
} | |
/* | |
* Use this hook to create a memoized callback instead of the original one | |
*/ | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export function useCallback(callback: (...args: any[]) => any, deps: any[]) { | |
return useCallbackBase(memoizeCallback(callback), deps) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment