Welcome! Please see the About page for a little more info on how this works.

+2 votes
in ClojureScript by
edited by

Let's say I have following component with a local state and some watching logic:

(defn some-component []
  (r/with-let [local-state (r/atom {...})
               _ (add-watch local-state :on-change handle-change)]
    [:div ...]))

Should I care about removing the watcher (if yes, what's a best way to do that), or it will happen automatically when the component does unmount.

2 Answers

+1 vote
by
 
Best answer

I just looked at the source code and found following

  (-add-watch [this key f]
    (set! (.-watches this) (assoc watches key f))
    this)

source

So I think it depends on scope. In my case the local-state atom is within a closure, thus once it removed, all its watchers also should be removed automatically. However, for atoms which are in global scope, watchers should be removed by hand if they are not need anymore.

0 votes
by

jahson in the Slack chat pointed at a similar question:
https://www.reddit.com/r/Clojure/comments/8k3ku0/do_i_need_to_removewatch_in_reagent_components/

"remove-watch should be called in the finally clause. React & Reagent are not implicitly aware of you calling add-watch to an atom. I don't think it's guaranteed, even if the atom is garbage collected, that the watch won't stick around in memory."

To remove a watcher we can use finally clause within r/with-let macro.

...