useMemoizedFn
A hook to declare a memoized function
Installation
npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-memoized-fn.json"pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-memoized-fn.json"yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-memoized-fn.json"bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-memoized-fn.json"Copy and paste the following code into your project.
import { useMemo, useRef } from 'react'
type noop = (this: any, ...args: any[]) => any
type PickFunction<T extends noop> = (
this: ThisParameterType<T>,
...args: Parameters<T>
) => ReturnType<T>
export function useMemoizedFn<T extends noop>(fn: T) {
const fnRef = useRef<T>(fn)
// why not write `fnRef.current = fn`?
// https://github.com/alibaba/hooks/issues/728
fnRef.current = useMemo<T>(() => fn, [fn])
const memoizedFn = useRef<PickFunction<T>>(undefined)
if (!memoizedFn.current) {
memoizedFn.current = function (this, ...args) {
return fnRef.current.apply(this, args)
}
}
return memoizedFn.current
}API
type noop = (this: any, ...args: any[]) => any
type PickFunction<T extends noop> = (
this: ThisParameterType<T>,
...args: Parameters<T>
) => ReturnType<T>
/**
* A hook to declare a memoized function
* @param fn - The function to declare as a memoized function
* @returns The memoized function
*/
export function useMemoizedFn<T extends noop>(fn: T): PickFunction<T>Credits
Last updated on