Created
April 18, 2022 00:03
-
-
Save MarekZeman91/9dc4f4a98abd6a49f1cc976fc81ef628 to your computer and use it in GitHub Desktop.
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 { 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