Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created April 18, 2022 00:03
Show Gist options
  • Save MarekZeman91/9dc4f4a98abd6a49f1cc976fc81ef628 to your computer and use it in GitHub Desktop.
Save MarekZeman91/9dc4f4a98abd6a49f1cc976fc81ef628 to your computer and use it in GitHub Desktop.
import { useRef } from 'react';
export const useObject = <T extends Record<string, any | unknown>>(obj: T | undefined): T => {
const safeObj = (obj || {}) as T;
const cached = useRef(safeObj);
const { current } = cached;
if (current === safeObj) return safeObj;
const keys = Object.keys({ ...current, ...safeObj });
for (const key of keys) {
if (current[key] !== safeObj[key]) {
cached.current = safeObj;
break;
}
}
return safeObj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment