Fork me on GitHub
#react
<
2021-10-05
>
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)
                                                 (on-change))))
                        #(remove-watch atom* key)))
                    #js [atom*])
        get-value (r/useCallback #(deref atom*) #js [atom*])]
    (useSyncExternalStoreExtra subscribe get-value nil identity =)))

lilactown16:10:43

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

lilactown16:10:46

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