Created
February 10, 2020 12:22
-
-
Save sibelius/a151a181f7ec39b0a58a04fcf77d0105 to your computer and use it in GitHub Desktop.
useMemo for arrays
This file contains hidden or 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
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