mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Also reduce max line width to 100. And remove `lint:types` step for commit sequence, it bothers when committing incomplete (wip) changes.
23 lines
624 B
TypeScript
23 lines
624 B
TypeScript
import { useRef } from 'react';
|
|
import { useFirstMountState } from './useFirstMountState';
|
|
|
|
export type Predicate<T> = (prev: T | undefined, next: T) => boolean;
|
|
|
|
const strictEquals = <T>(prev: T | undefined, next: T) => prev === next;
|
|
|
|
export default function usePreviousDistinct<T>(
|
|
value: T,
|
|
compare: Predicate<T> = strictEquals
|
|
): T | undefined {
|
|
const prevRef = useRef<T>();
|
|
const curRef = useRef<T>(value);
|
|
const isFirstMount = useFirstMountState();
|
|
|
|
if (!isFirstMount && !compare(curRef.current, value)) {
|
|
prevRef.current = curRef.current;
|
|
curRef.current = value;
|
|
}
|
|
|
|
return prevRef.current;
|
|
}
|