Last active
May 18, 2019 23:39
-
-
Save Lucretiel/e5ec48e02adca2d0d220c50559ffaa72 to your computer and use it in GitHub Desktop.
React hook for creating callback functions in a loop to pass to individual components
This file contains hidden or 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 "lodash" | |
/** | |
* Helper for passing a callback to each component in a loop. Given a callback | |
* with the signature (key, ..args), returns a new factory with the signature | |
* (key) => (...args). When called with a key, returns a wrapper function taking | |
* (...args) wich calls the original callback. This wrapper function is guaranteed | |
* to be the same for any given key. | |
* | |
* The callback must have NO dependencies that might change between renders. It | |
* can only use useState setters, useRef references, etc. | |
*/ | |
const useKeyedCallback = function< | |
Ret, | |
Key, | |
Args extends Array<any> | |
>( | |
callback: (key: Key, ...args: Args) => Ret, | |
): | |
(key: Key) => (...args: Args) => Ret | |
{ | |
return React.useMemo(() => memoize((key) => (...args) => callback(key, ...args)), []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment