reactjs - Clojurescript, Reagent: pass atoms down as inputs, or use as global variables? -
i'm writing clojurescript app, using reagent make components reactive.
i have simple question. should
- pass atoms inputs through components, or
- use atoms global variables , let them 'side-affect' components?
in tutorial use latter option, in trying keep functions pure opted former.
am correct in saying using them global variables (in addition being less verbose when defining component inputs) prevents re-rendering of whole parent components atom's state not used?
if make components accept atoms arguments, can make them more reusable , easier test.
this true if opt keeping entire application state in single atom, passing down child components using cursors.
;; setup single instance of global state (defonce app-state (reagent/atom {:foo 0 :bar 0}) ;; define generic counter component knows ;; nothing global state (defn counter [count] [:div [:button {:onclick #(swap! count inc) "+"] [:span @count]]) ;; define counter components , give them access ;; specific context within global state (defn app [state] [counter (reagent/cursor app-state [:foo])] [counter (reagent/cursor app-state [:bar])])
you can go 1 step further if decide use reagent re-frame. re-frame encourages build app specific architecture looks this.
app-db > subscriptions ^ handlers v ^ events < components
rather writing components , hooking them straight global atom (
app-db
), writesubscriptions
functions select/query dataapp-db
, pass along components wheneverapp-db
changed.then, rather component messing around
app-db
directly, component createsevents
small pieces of data describe intent of component.these events sent
handlers
, functions takeevent
, currentapp-db
arguments , return newapp-db
. existingapp-db
replaced, triggering subscribers pass data down components , on.
it's helpful if find reagent project getting bit tangled , re-frame readme great read, whether decide use or not.
Comments
Post a Comment