Skip to content

Instantly share code, notes, and snippets.

@geraldodev
Last active October 6, 2020 19:49
Show Gist options
  • Save geraldodev/a27a7ec31c91610190b9e3911a2f54c6 to your computer and use it in GitHub Desktop.
Save geraldodev/a27a7ec31c91610190b9e3911a2f54c6 to your computer and use it in GitHub Desktop.
extracted from helix zulip chat from a message of wilkerlucio
(ns app.util.hooks
(:require
["react" :refer [useState]]
))
(defn use-state
"A simple wrapper around React/useState. Returns a cljs vector for easy destructuring"
[initial-value]
(into-array (useState initial-value)))
(defn use-atom-state [initial-value]
(let [[value set-value!] (use-state initial-value)]
(reify
IDeref
(-deref [o] value)
IReset
(-reset! [o new-value] (doto new-value set-value!))
ISwap
(-swap! [a f] (set-value! f))
(-swap! [a f x] (set-value! #(f % x)))
(-swap! [a f x y] (set-value! #(f % x y)))
(-swap! [a f x y more] (set-value! #(apply f % x y more))))))
(comment
(defnc Example
[]
(let [a (use-atom-state 10)]
(div
(d/label @a)
(d/button {:on-click (fn [e]
(swap! a inc))}
"plus"))))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment