Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created February 10, 2020 12:22
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sibelius/a151a181f7ec39b0a58a04fcf77d0105 to your computer and use it in GitHub Desktop.
Save sibelius/a151a181f7ec39b0a58a04fcf77d0105 to your computer and use it in GitHub Desktop.
useMemo for arrays
const arrayCompare = (a: string[], b: string[]) => {
if (a.length !== b.length) {
return false;
}
for (const item of a) {
if (b.indexOf(item) === -1) {
return false;
}
}
return true;
};
const usePrevious = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const useMemoArray = (arr, callback) => {
const previousArr = usePrevious(arr);
const arrayHasChanged = arrayCompare(arr, previousArr);
return useMemo(callback, arrayHasChanged);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment