Skip to content

Instantly share code, notes, and snippets.

@huynhducduy
Last active April 4, 2024 04:44
Show Gist options
  • Save huynhducduy/03790a82e390413a649db7c6ec160547 to your computer and use it in GitHub Desktop.
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)
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