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