@wilkerlucio I've got to a point that I need a pointer with use-state, and I saw you use-atom-state example on zulip log. Do you have anything else to add to that implementation ? Have you gone for it ? https://gist.github.com/geraldodev/a27a7ec31c91610190b9e3911a2f54c6
@geraldodev hello, I did used something similar in the past, but it's been a while, I personally like the approach, just not sure if that implementation as-is is the best, one thing you can improve on that is use a defrecord
to define a type instead of generating one every time with reify
I found something here:
(deftype ReactAtomState [value set-value!]
IDeref
(-deref [o] value)
IReset
(-reset! [o new-value] (doto new-value set-value!))
ISwap
(-swap! [a f] (set-value! (f value)))
(-swap! [a f x] (set-value! (f value x)))
(-swap! [a f x y] (set-value! (f value x y)))
(-swap! [a f x y more] (set-value! (apply f value x y more))))
(defn use-state-atom [initial-value]
(let [[value set-value!] (use-state initial-value)]
(->ReactAtomState value set-value!)))
@wilkerlucio thank you.
I will caution that this couples reading with writing, and also doesn’t act exactly the same as an atom
swapping and then derefing in the same tick will still yield the old value until next render
As long as you’re fine with that, go forth. But those were the reasons I ended up removing the hook from helix core hooks
It can certainly be useful sometimes. I find that passing in a value and an on-change callback is what I prefer nowadays
(defnc ContratualizacaoGraph
[]
(let [
[pilha-vis set-pilha-vis] (hooks/use-state [])
fn-conj-nivel (fn [{:keys [type] :as m}] )
] )
@lilactown I need pass function fn-conj-nivel on the render to allow changing of the state. The problem is that pilha-vis is a value and not a pointer, and set-pilha-vis changes the entire value. I need fn-conj-nivel to refer to the actual state, but because its a value it establish a closure with the initial value ([]).
sorry my english
I don’t think that wrapping it in a type that implements deref will help you here
fn-conj-nivel
as it’s written now will be recreated each render. which means it will close over each new value of pilha-vis
@lilactown You are right
Does anybody know an article or library about using a more event driven approach (similar to re-frame) with hooks? I have the impression that I’m sprinkling use-state
or custom hooks which build on use-state
all over the code which makes reasoning about the “global” state of the application quite tricky.
use-reducer is a nice improvement over use-state for complex components