Skip to content

Instantly share code, notes, and snippets.

@whaaaley
Last active June 18, 2021 04:53
Show Gist options
  • Save whaaaley/e67a404abe3706ad77f7df494217cc60 to your computer and use it in GitHub Desktop.
Save whaaaley/e67a404abe3706ad77f7df494217cc60 to your computer and use it in GitHub Desktop.
/**
*
* 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