Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Created August 28, 2019 16:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tannerlinsley/83159986c87e343bb562dd20e6394bc9 to your computer and use it in GitHub Desktop.
Save tannerlinsley/83159986c87e343bb562dd20e6394bc9 to your computer and use it in GitHub Desktop.
export default function useMicroMemo() {
const memosRef = React.useRef(new Map());
return (id, updater, deps) => {
const memo = memosRef.current.get(id) || {};
let shouldUpdate;
if (!memo.deps) {
shouldUpdate = true;
} else if (deps.length !== memo.deps.length) {
shouldUpdate = true;
} else {
shouldUpdate = deps.some((dep, index) => {
return dep !== memo.deps[index];
});
}
if (shouldUpdate) {
memo.deps = deps;
memo.value = typeof updater === "function" ? updater() : updater;
memosRef.current.set(id, memo);
}
return memo.value;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment