Fork me on GitHub
Roman Liutikov12:10:33

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)
                        #(remove-watch atom* key)))
                    #js [atom*])
        get-value (r/useCallback #(deref atom*) #js [atom*])]
    (useSyncExternalStoreExtra subscribe get-value nil identity =)))


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


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