react

martinklepsch 2021-08-03T10:17:03.001100Z

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

martinklepsch 2021-08-03T10:17:37.001900Z

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

martinklepsch 2021-08-03T11:01:11.002900Z

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

lilactown 2021-08-03T15:23:03.004100Z

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 =

lilactown 2021-08-03T15:49:27.004600Z

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

lilactown 2021-08-03T15:51:06.005300Z

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

lilactown 2021-08-03T15:52:45.006900Z

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

lilactown 2021-08-03T15:53:10.007500Z

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