Fork me on GitHub
#helix
<
2020-10-06
>
geraldodev19:10:29

@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

wilkerlucio19:10:38

@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

wilkerlucio19:10:54

I found something here:

wilkerlucio19:10:55

(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!)))

lilactown19:10:17

I will caution that this couples reading with writing, and also doesn’t act exactly the same as an atom

lilactown19:10:08

swapping and then derefing in the same tick will still yield the old value until next render

lilactown19:10:12

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

lilactown19:10:39

It can certainly be useful sometimes. I find that passing in a value and an on-change callback is what I prefer nowadays

geraldodev20:10:22

(defnc ContratualizacaoGraph [] (let [ [pilha-vis set-pilha-vis] (hooks/use-state []) fn-conj-nivel (fn [{:keys [type] :as m}] )

] )

geraldodev20:10:34

@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 ([]).

geraldodev20:10:46

sorry my english

lilactown20:10:34

I don’t think that wrapping it in a type that implements deref will help you here

lilactown20:10:41

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

ordnungswidrig21:10:53

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.

lilactown22:10:21

use-reducer is a nice improvement over use-state for complex components