react-use/src/usePreviousDistinct.ts
Paul Sachs 6c3e569db6 feat: add usePreviousDistinct (#551)
* feat: add usePreviousDistinct

* Cleanup

* Added storybook docs

* improve demo in docs
2019-08-25 21:20:44 +02:00

20 lines
450 B
TypeScript

import { useRef } from 'react';
function strictEquals<T>(prev: T | undefined, next: T) {
return prev === next;
}
export default function usePreviousDistinct<T>(
value: T,
compare: (prev: T | undefined, next: T) => boolean = strictEquals
) {
const prevRef = useRef<T>();
const curRef = useRef<T>();
if (!compare(curRef.current, value)) {
prevRef.current = curRef.current;
curRef.current = value;
}
return prevRef.current;
}