Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 09:57
Show Gist options
  • Select an option

  • Save freddi301/c8b102d7615c0518dc4dcfa70194990e to your computer and use it in GitHub Desktop.

Select an option

Save freddi301/c8b102d7615c0518dc4dcfa70194990e to your computer and use it in GitHub Desktop.
useMemoizedCallbacks #react #hook
import { useMemo } from "react";
import { memoize } from "lodash";
/**
* @description useful for callback that are passed to repeated component
* @example
* const makeRemove=useMemoizedCallback((date:Date)=>()=>{},String,[]);
* ...
* <ol>calendarEvents.map(calendarEvent => <li onClick={makeRemove(calendarEvent)}>{calendarEvent.toLocaleString()}</li>)</ol>
*/
export function useMemoizeCallback<
F extends (...args: any[]) => any,
K extends (...args: Parameters<F>) => any
>(fn: F, resolver: K | undefined, inputs: any[]): F {
return useMemo(() => memoize(fn, resolver as any), [fn, resolver, ...inputs]); // eslint-disable-line
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment