Skip to content

Instantly share code, notes, and snippets.

@david-arteaga
Created April 13, 2022 15:20
Show Gist options
  • Save david-arteaga/dd22249bea62a8389639877a67cd43b0 to your computer and use it in GitHub Desktop.
Save david-arteaga/dd22249bea62a8389639877a67cd43b0 to your computer and use it in GitHub Desktop.
[useLogKeyDifferences] #react #debugging
import { useRef } from 'react';
export default function useLogKeyDifferences<Type>(object: Type) {
const objectRef = useRef<undefined | Type>(undefined);
const previousObject = objectRef.current;
objectRef.current = object;
const differentKeys = new Set<keyof Type>();
(Object.keys(object) as (keyof Type)[]).forEach((key) => {
const prev = previousObject?.[key];
const current = object[key];
if (prev !== current) {
differentKeys.add(key);
}
});
(Object.keys(previousObject ?? {}) as (keyof Type)[]).forEach((key) => {
const prev = previousObject?.[key];
const current = object[key];
if (prev !== current) {
differentKeys.add(key);
}
});
differentKeys.forEach((key) => {
console.log('KeyDifference::', key, ({
previous: previousObject?.[key],
current: object[key],
}));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment