Created
May 20, 2025 08:45
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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