File tree Expand file tree Collapse file tree 1 file changed +31
-5
lines changed
Expand file tree Collapse file tree 1 file changed +31
-5
lines changed Original file line number Diff line number Diff line change 44 [hx.hooks :as hooks :refer [<-state <-effect <-context]]
55 [" react" :as react]))
66
7+ ; ;
8+ ; ; A simple counter
9+ ; ;
10+
711(defnc Simple [_]
812 (let [state (<-state 0 )]
913 [:<>
1317(dc/defcard simple
1418 (hx/f [Simple]))
1519
20+
21+ ; ;
22+ ; ; A timer that increments each second
23+ ; ;
24+
1625(defnc Timer
1726 [opts]
1827 (let [seconds (<-state 0 )]
2736(dc/defcard timer
2837 (hx/f [Timer]))
2938
39+
40+ ; ;
41+ ; ; Using React Context + Hooks for global state management
42+ ; ;
43+
3044(def app-state (react/createContext ))
3145
3246(defnc App [{:keys [children]}]
33- (let [state (<-state {:counter 0 })]
47+ (let [state (<-state {})]
3448 [(.-Provider app-state) {:value state}
3549 children]))
3650
37- (defnc Counter [_]
51+ (defnc CounterConsumer [_]
3852 (let [state (<-context app-state)
3953 {:keys [counter]} @state]
4054 [:<>
4155 [:div " Counter: " counter]
4256 [:button {:on-click #(swap! state update :counter inc)} " inc" ]]))
4357
44- (defnc PrintState [_]
58+ (defnc PrintStateConsumer [_]
4559 (let [state (<-context app-state)]
4660 [:pre (prn-str @state)]))
4761
62+ (defnc TimerConsumer [_]
63+ (let [state (<-context app-state)
64+ {:keys [timer]} @state]
65+ (<-effect (fn []
66+ (let [id (js/setInterval #(swap! state update :timer inc) 1000 )]
67+ (fn []
68+ (js/clearInterval id))))
69+ [])
70+ [:<>
71+ [:div " Timer: " timer]]))
72+
4873(dc/defcard context
4974 (hx/f [App
50- [PrintState]
51- [Counter]]))
75+ [PrintStateConsumer]
76+ [TimerConsumer]
77+ [CounterConsumer]]))
5278
You can’t perform that action at this time.
0 commit comments