Skip to content

Instantly share code, notes, and snippets.

@MikelArnaiz
Created November 15, 2022 10:19
Show Gist options
  • Save MikelArnaiz/0cf5ac810c8e39a89feeb989d8ba2505 to your computer and use it in GitHub Desktop.
Save MikelArnaiz/0cf5ac810c8e39a89feeb989d8ba2505 to your computer and use it in GitHub Desktop.
Use useWarningOnRefChangedButEqualDeepCompare
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