Anyone happen to have an implementation of this useMemoCompare they could share? https://usehooks.com/useMemoCompare/
Looks like a generally interesting approach to deal with complex data structures in useEffect dependencies
I think I can also just use useMemo for my particular use case
I do have a hook that I call use-stable-identity which uses Clojure equality to always return the previous one if the value passed in to is =
(defn use-stable-identity
"Caches `x`. When a new `x` is passed in, returns new `x` only if it is
not structurally equal to the previous `x`.
Useful for optimizing `use-effect`, `use-memo` et. al. when you have two
values that might be structurally equal but referentially different."
[x]
(let [-x (react/useRef x)
;; if they are equal, return the prev one to ensure ref equality
x' (if (= x (.-current -x))
(.-current -x)
x)]
;; Set the ref to be the last value that was succesfully used to render
(react/useEffect (fn []
(set! (.-current -x) x)
js/undefined)
#js [x'])
x'))it's basically useMemoCompare but assumes = is the compare you want to use. you could parameterize that
IME it's only really useful in a couple circumstances, for instance you've got a complex data structure that is being serialized from somewhere (i.e. a network request, or local storage), changes relatively infrequently and you want to detect if it's actually different than the previous value
otherwise it's usually cheaper to not reconstruct a new equivalent value frequently
https://clojurians.slack.com/archives/CRRJBCX7S/p1628011930063000