Skip to content

Instantly share code, notes, and snippets.

@huynhducduy
Forked from tannerlinsley/useGlobalMemo.js
Created May 19, 2024 12:51
Show Gist options
  • Save huynhducduy/07b5c62cd0480bba67ad8debad22bf6d to your computer and use it in GitHub Desktop.
Save huynhducduy/07b5c62cd0480bba67ad8debad22bf6d to your computer and use it in GitHub Desktop.
useGlobalMemo is a React hook that lets you share memoizations across an entire app using a unique key.
const cache = {}
export default function useGlobalMemo (key, fn, deps) {
if (!cache[key]) {
cache[key] = {
subs: 0,
deps,
value: fn(),
}
} else {
const oldDeps = cache[key].deps
if (oldDeps.length !== deps || oldDeps.some((d, i) => deps[i] !== d)) {
cache[key] = {
deps,
value: fn()
}
}
}
React.useEffect(() => {
cache[key].subs += 1
return () => {
cache[key].subs -= 1
if (!cache[key].subs) {
delete cache[key]
}
}
}, [])
return cache[key].value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment