Fork me on GitHub
#reagent
<
2022-09-27
>
Dameon23:09:22

I wanted to check my understanding. For reagent/atom , it has to be defined above the scope of any component where it’s used. Is that because a change to that atom causes a re-render of the whole component where the atom changed? Essentially causing it to get redefined every re-render.

(defn counting-component []
 (let [click-count (r/atom)]
  [:div
   "The atom " [:code "click-count"] " has value: "
   @click-count ". "
   [:input {:type "button" :value "Click me!"
            :on-click #(swap! click-count inc)}]]))

VS.

(defn counting-component []
 (let [click-count (r/atom)]
  (fn []
   [:div
    "The atom " [:code "click-count"] " has value: "
    @click-count ". "
    [:input {:type "button" :value "Click me!"
             :on-click #(swap! click-count inc)}]])))

p-himik08:09:03

Your understanding is correct. Also, to help with such simple instances of form-2 components, there's reagent.core/with-let.

p-himik08:09:09

So you could instead write:

(defn counting-component []
  (r/with-let [click-count (r/atom nil)]  ;; Note that you must provide an argument, there's no 0 arity in `r/atom`.
    [:div ...]))

Dameon15:09:51

That's cool! That'll clean things up a bit. Thanks :)

👍 1