Skip to content

Instantly share code, notes, and snippets.

@akonwi
Last active March 6, 2020 19:23
Show Gist options
  • Save akonwi/cad7d93d8a7d332b94fd67c529660ef0 to your computer and use it in GitHub Desktop.
Save akonwi/cad7d93d8a7d332b94fd67c529660ef0 to your computer and use it in GitHub Desktop.
function useDidChange(cb: (previous: any[]) => void, deps: any[]) {
const isMountedRef = React.useRef(false);
const cbRef = React.useRef(cb);
React.useEffect(() => {
cbRef.current = cb;
}, [cb]);
const previousRef = React.useRef(deps);
React.useEffect(() => {
if (isMountedRef.current) {
cbRef.current(previousRef.current);
}
previousRef.current = deps;
}, deps);
React.useEffect(() => {
isMountedRef.current = true;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment