Fork me on GitHub
#react
<
2021-08-03
>
martinklepsch10:08:03

Anyone happen to have an implementation of this useMemoCompare they could share? https://usehooks.com/useMemoCompare/

martinklepsch10:08:37

Looks like a generally interesting approach to deal with complex data structures in useEffect dependencies

martinklepsch11:08:11

I think I can also just use useMemo for my particular use case

lilactown15:08:03

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 =

lilactown15:08:27

(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'))

lilactown15:08:06

it's basically useMemoCompare but assumes = is the compare you want to use. you could parameterize that

lilactown15:08:45

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

lilactown15:08:10

otherwise it's usually cheaper to not reconstruct a new equivalent value frequently