Skip to content
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
78 lines (64 sloc) 1.77 KB
(ns hooks-demo.hooks
(:require ["react" :as react]
(def <-state react/useState)
(def <-effect react/useEffect)
;; Example of a custom hook to watch atoms
(defn <-deref
;; if no deps are passed in, we assume we only want to run
;; subscrib/unsubscribe on mount/unmount
([a] (<-deref a []))
([a deps]
;; create a react/useState hook to track and trigger renders
(let [[v u] (<-state @a)]
;; react/useEffect hook to create and track the subscription to the iref
(fn []
(println "adding watch")
(add-watch a :use-atom
;; update the react state on each change
(fn [_ _ _ v'] (u v')))
;; return a function to tell react hook how to unsubscribe
(println "removing watch")
(remove-watch a :use-atom)))
;; pass in deps vector as an array
(clj->js deps))
;; return value of useState on each run
;; Example of using re-frame subscriptions
(defn <-sub
(<-sub query []))
([query deps]
(let [r (react/useMemo
#(re-frame.core/subscribe query)
(clj->js deps))
[v u] (react/useState @r)]
(fn []
(let [t (reagent.core/track! #(u @r))]
#(reagent.core/dispose! t)))
(clj->js deps))
;; credit Roman Liutikov (@roman01la)
(deftype AtomifiedReactRef [react-ref]
(-deref [_]
(first react-ref))
(-reset! [_ v']
((second react-ref) v')
(-swap! [o f]
(-reset! o (f (-deref o)))))
(defn <- [f & args]
(AtomifiedReactRef. (apply f args)))
(defn <-!state [initial]
(<- react/useState initial))
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.