import { useRef } from 'react'; import { useFirstRender } from './use-first-render'; import { CompareFunction, strictEquals } from './utils'; /** * Get the previous state or prop based on the comparation with current value. * * • * * @param state State (or prop). * @param compareFn Function to compare current value with previous value (default strict equal). */ export function usePreviousDistinct(state: T, compareFn: CompareFunction = strictEquals) { const prevRef = useRef(); const curRef = useRef(state); const isFirstRender = useFirstRender(); if (!isFirstRender && !compareFn(curRef.current, state)) { prevRef.current = curRef.current; curRef.current = state; } return prevRef.current; }