Fork me on GitHub
#reagent
<
2018-07-09
>
nijk11:07:20

I haven’t been able to find much in the way of documentation on this question so I thought it best to ask here: When creating a component that requires local state, is it advisable to use (reagent/set-state this {:foo 1})/`(:foo (reagent/state this))` or the !state (reagent/atom ...)/`(:foo @!state)` pattern? I’m aware that the former uses an atom as well, but I’m struggling to access the component state in reagent-render when using the former.

martinklepsch11:07:26

@nick828 I think it’s more common to use the latter reagent/atom way, or at least haven’t worked with any codebases that used reagent/set-state in any notable fashion

nijk12:07:08

Thanks @martinklepsch, is the reagent/set-state usage considered to be old/deprecated then?

lilactown15:07:26

I think it's just pretty un-idiomatic, both for reagent and clojure in general

lilactown15:07:08

usually if you have some mutable state, you put those in a ref of some kind (e.g. an atom) to manage them. reagent atom's allow you maintain that idiom

pesterhazy17:07:01

@nick828 I would say it's deprecated

pesterhazy17:07:22

the funny thing is it doesn't actually use React's this.state - it also uses a Ratom internally

pesterhazy17:07:54

much better to simply use a ratom bound in a let binding: (defn my-ui [] (let [!state (r/atom nil)] (fn [props] [:input {:on-change (fn [e] (reset! !state (-> e .-target .-value)))}])))

pesterhazy17:07:08

makes it obvious what's going on

pesterhazy17:07:54

if you want to use this.state, that's also possible though not convenient. See this PR by @juhoteperi: https://github.com/reagent-project/reagent/pull/381/files

pesterhazy17:07:15

IME you need that only when you're dealing with input fields