Last active
June 18, 2021 04:53
-
-
Save whaaaley/e67a404abe3706ad77f7df494217cc60 to your computer and use it in GitHub Desktop.
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
/** | |
* | |
* Memoization utility | |
* | |
* @param cb - callback to determine when to return stale children | |
* @param key - name of the memo | |
* @param target - children you want to memoize | |
* | |
*/ | |
const EMPTY_ARR = Object.freeze([]) | |
const INIT_STORAGE = { stale: EMPTY_ARR, target: EMPTY_ARR } | |
const memoize = cb => { | |
const storage = {} | |
return (key, target) => { | |
const ref = storage[key] = storage[key] ?? INIT_STORAGE | |
return cb(target) ? (ref.target = ref.stale) : (ref.stale = target) | |
} | |
} | |
/** | |
* | |
* Your component | |
* | |
*/ | |
const memo = memoize(target => target.length === 0) | |
const Component = props => { | |
return ( | |
<div> | |
<div>{memo('foo', props.oneMillionChildren)}</div> | |
<div>{memo('bar', props.twentyThousandChildren)}</div> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment