Hey all, could I get your thoughts on best practices when it comes to passing props and state around between components?
Say I've got two components called wrapper
and demo
. The wrapper
namespace has a state atom that I'd like to use in demo
. My first instinct is to pass that state atom as a prop to demo
:
(ns core
(:require
[reagent.core :as r]
[reagent.dom :as rdom]
[somecomponent] :refer [demo]))
(defonce state (r/atom "royal blue"))
(defn wrapper []
[demo state])
(rdom/render [wrapper] (.getElementById js/document "root"))
... and then in the demo
namespace:
(ns somecomponent)
(defn demo [prop]
(:p (str "the color of the pen is " @prop)))
But if I wanted, I could also require that atom directly from the core
namespace itself, which seems a lot easier, especially for nested components :
(ns somecomponent)
(defn demo []
(:p (str "the color of the pen is " @core/state)))
It seems a lot easier, but are there any drawbacks you can see to this method? Gotchas? Things that might trip me up if I get too deep into requiring atoms directly instead of passing them as props and relying on the underlying React API to trigger re-renders?> But if I wanted, I could also require that atom directly from the core namespace itself It would create a circular dependency, so you would have to move the ratom elsewhere. Using ratoms directly creates coupling, prevents reuse, makes explicit things implicit, but decreases the amount of arguments. Passign ratoms as props is the opposite of that.
Ah, right, I hadn't considered that part. I guess I could have a whole separate atoms namespace with all my app state, and require everything directly from there. But if I'm going that far then I've already gone most of the way towards re-frame and may as well use a library instead of a home-rolled global app state solution. Thanks for the help 🙂