react

Roman Liutikov 2021-10-05T12:45:33.078700Z

Here’s a hook using useSyncExternalStoreExtra to subscribe to atoms/subscriptions

(defn use-atom [v]
  (let [[atom* _] (r/useState v)
        subscribe (r/useCallback
                    (fn [on-change]
                      (let [key (gensym "use-atom")]
                        (add-watch atom* key (fn [_ _ old-v new-v]
                                               (when (not= old-v new-v)
                                                 (on-change))))
                        #(remove-watch atom* key)))
                    #js [atom*])
        get-value (r/useCallback #(deref atom*) #js [atom*])]
    (useSyncExternalStoreExtra subscribe get-value nil identity =)))

lilactown 2021-10-05T16:02:58.079Z

nice

lilactown 2021-10-05T16:03:43.079800Z

I do wish they put some thought into how to support libs like MobX and reagent which have boxes that lazily calculate their value on subscribe

lilactown 2021-10-05T16:04:46.080600Z

the only way to avoid memory leaks rn is to do ref counting and manual cleanup