diff --git a/examples/workshop/state.cljs b/examples/workshop/state.cljs index 283048a..eb3f3ff 100644 --- a/examples/workshop/state.cljs +++ b/examples/workshop/state.cljs @@ -4,6 +4,10 @@ [hx.hooks :as hooks :refer [<-state <-effect <-context]] ["react" :as react])) +;; +;; A simple counter +;; + (defnc Simple [_] (let [state (<-state 0)] [:<> @@ -13,6 +17,11 @@ (dc/defcard simple (hx/f [Simple])) + +;; +;; A timer that increments each second +;; + (defnc Timer [opts] (let [seconds (<-state 0)] @@ -27,26 +36,43 @@ (dc/defcard timer (hx/f [Timer])) + +;; +;; Using React Context + Hooks for global state management +;; + (def app-state (react/createContext)) (defnc App [{:keys [children]}] - (let [state (<-state {:counter 0})] + (let [state (<-state {})] [(.-Provider app-state) {:value state} children])) -(defnc Counter [_] +(defnc CounterConsumer [_] (let [state (<-context app-state) {:keys [counter]} @state] [:<> [:div "Counter: " counter] [:button {:on-click #(swap! state update :counter inc)} "inc"]])) -(defnc PrintState [_] +(defnc PrintStateConsumer [_] (let [state (<-context app-state)] [:pre (prn-str @state)])) +(defnc TimerConsumer [_] + (let [state (<-context app-state) + {:keys [timer]} @state] + (<-effect (fn [] + (let [id (js/setInterval #(swap! state update :timer inc) 1000)] + (fn [] + (js/clearInterval id)))) + []) + [:<> + [:div "Timer: " timer]])) + (dc/defcard context (hx/f [App - [PrintState] - [Counter]])) + [PrintStateConsumer] + [TimerConsumer] + [CounterConsumer]]))