Created
November 15, 2022 10:19
-
-
Save MikelArnaiz/0cf5ac810c8e39a89feeb989d8ba2505 to your computer and use it in GitHub Desktop.
Use useWarningOnRefChangedButEqualDeepCompare
This file contains 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 { useEffect } from 'react'; | |
import isEqual from 'lodash-es/isEqual'; | |
export const usePrevious = <T>(value: T) => { | |
const ref = useRef<T>(); | |
useEffect(() => { | |
ref.current = value; | |
}); | |
return ref.current; | |
}; | |
export const useWarningOnRefChangedButEqualDeepCompare = <T>( | |
current: T, | |
log: string | |
) => { | |
const prev = usePrevious(current); | |
useEffect(() => { | |
if ( | |
prev !== undefined && | |
prev !== current && // are different refs | |
isEqual(prev, current) // has same value | |
) { | |
// eslint-disable-next-line no-console | |
console.warn(`Ref changed but value is equal, ${log}`, current); | |
} | |
}, [current, log, prev]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment