useMemoFn() - Shortcut for memoizing function call results

React’s useMemo() is used to memoize the result of a function call. This helps increasing performance of the render cycle of React components. However many calls to useMemo() follow a simple pattern and still require quite some repetitive code which we want to reduce:

const fibonacciResult = useMemo(() => fibonacci(number), [fibonacci, number])

const heavyResult = useMemo(() => heavyComputation(arg1, arg2, arg3), [heavyComputation, arg1, arg2, arg3])

Both the function reference itself as well as all its arguments have to be repeated in useMemo’s dependency array. In order to avoid repeating this boilerplate, it would be great if we could just write:

const fibonacciResult = useMemoFn(fibonacci, number)

const heavyResult = useMemoFn(heavyComputation, arg1, arg2)

Here’s how useMemoFn() can be implemented:

//eslint-disable-next-line
const useMemoFn = (fn, ...args) => useMemo(() => fn.apply(null, args), [fn, ...args])

//eslint-disable-next-line surpresses some of React’s warnings due to the dynamic implementation of this hook.

comments powered by Disqus