Skip to content

Instantly share code, notes, and snippets.

@tlux
Created May 20, 2025 08:45
Show Gist options
  • Save tlux/b4c8e6c05ad2b0d3fcd39eacfebc328c to your computer and use it in GitHub Desktop.
Save tlux/b4c8e6c05ad2b0d3fcd39eacfebc328c to your computer and use it in GitHub Desktop.
Hook that checks if a passed value has changed based on the provided equality function and returns the old instance of the * value if it has not changed
import { isEqual } from 'lodash-es';
import { useEffect, useRef, useState } from 'react';
/**
* Checks if a passed value has changed based on the provided equality function and returns the old instance of the
* value if it has not changed.
*
* @param value The value that is compared.
* @param equalFn A function that compares the old and the new value. Defaults to `lodash.isEqual`.
*/
export function useDistinct<T>(value: T, equalFn: (a: T, b: T) => boolean = isEqual) {
const equalFnRef = useRef(equalFn);
const [current, setCurrent] = useState(value);
useEffect(() => {
if (!equalFnRef.current(current, value)) {
setCurrent(value);
}
}, [current, value]);
return current;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment