Last active
June 4, 2018 14:33
-
-
Save jebarjonet/d7f2930f92fe9dbef2281037aab138d4 to your computer and use it in GitHub Desktop.
Memoized function accepting arguments (prevents React rerendering)
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 memoize from 'memoizee' | |
/** | |
* Returns memoized function accepting arguments (prevents React rerendering) | |
*/ | |
export const makeCallback = memoize( | |
(func, ...args) => (...additionalArgs) => func(...args, ...additionalArgs), | |
{ length: false }, | |
) | |
// TESTS | |
test('makeCallback', () => { | |
const func = value => value | |
const firstInstance = () => func(0) | |
const secondInstance = () => func(0) | |
expect(firstInstance).not.toBe(secondInstance) | |
// memoize callback | |
const firstMemoizedInstance = makeCallback(func, 0) | |
const secondMemoizedInstance = makeCallback(func, 0) | |
expect(firstMemoizedInstance).toBe(secondMemoizedInstance) | |
expect(secondMemoizedInstance()).toEqual(0) | |
const thirdMemoizedInstance = makeCallback(func, 1) | |
expect(firstMemoizedInstance).not.toBe(thirdMemoizedInstance) | |
expect(thirdMemoizedInstance()).toEqual(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment