Created
August 28, 2019 16:30
-
-
Save tannerlinsley/83159986c87e343bb562dd20e6394bc9 to your computer and use it in GitHub Desktop.
This file contains 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
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