nosco / hx

A simple, easy to use library for React development in ClojureScript.
MIT License
247 stars 16 forks source link

Implement additional protocols for Atomified react-state #11

Closed lilactown closed 5 years ago

lilactown commented 5 years ago

IWatchable, IEquiv, IHash, IPrintWithWriter would all be nice to have

orestis commented 5 years ago

I'm hijacking this issue to discuss about something that caught me a little bit unawares with Atomified.

I had this code:

(let [foo (<-state #{})]
 [:button {:on-click (fn [e] (swap! foo conj 1)
                                            (js/console.log @foo))}])

I would expect based on my Clojure experience that #{1} should be printed, but because react hasn't re-rendered anything yet, the value of the deref-ed state is still the original empty set.

I tried to work around this by relying on the return value of swap! which should be the new value, but the implementation of Atomified doesn't return anything.

I now wonder if the semantics of a Clojure atom make sense for this rendering lifecycle that React uses, where the new state is only available after a re-render.

orestis commented 5 years ago

A workaround for this is to manually update the deref-ed value, and then reset! it into the new state to trigger the rendering. So something like this:

(fn [e]
  (let [new-foo (conj foo 1)]
      (reset! foo new-foo)
      (js/console.log new-foo)))
lilactown commented 5 years ago

Hm. Yeah, useState is more like an agent than an atom, since updates are scheduled by React asynchronously.

And it schedules the update itself, not the value, so it's impossible to return the correct value from swap! without bugs.

lilactown commented 5 years ago

I think that we want to maintain the semantics of useState because it is the most correct when used in Concurrent React.

The question then is: do we drop the atom interface?

orestis commented 5 years ago

Good point. I like the ergonomics of seeing a deref in the code, and the usual atom stuff do look convenient. But, it does seem like a leaky abstraction. Using the plain useState isn’t that painful, and the semantics are actually less surprising. So perhaps dropping the atom interface is best at this point. Or at least documenting this with great big letters.

orestis commented 5 years ago

Re-reading this, I think @Lokeh you are up to something by saying "useState is more like an agent". I've never used Agents before, but reading the documentation I think it's definitely possible to expose this kind of semantics (or the subset that makes sense).

So for example instead of using the swap! and reset! which point to atoms and synchronous updates, we'd use send (or perhaps send->) that would just call setFoo behind the scenes.

Deref is still a thing with agents, but you get whatever the current value is, because the update happens on a different thread outside of your control.

mhuebert commented 5 years ago

I find myself wondering exactly what sort of bugs one might find when using ordinary atom semantics.

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI. [link]

It looks to me like one could adopt plain atom semantics, with the caveat that it is unsafe to reset/swap the atom during the render phase? This would be similar to allowed behaviour in class components:

 Warning: setState(...): Cannot update during an existing state transition 
(such as within `render` or another component's constructor). Render methods 
 should be a pure function of props and state; constructor side-effects are an anti-pattern, 
 but can be moved to `componentWillMount`.

One could have something like deferred-swap! or send for the exceptional case of wanting to trigger a state update from within the render. I'm not sure what the uses for that are, or if there are other reasons/places where synchronous mutations would be unsafe.

orestis commented 5 years ago

The issue I had was that I was assuming that inside the click handler I could access the new atom state:

(let [foo (<-state #{})]
  [:button {:on-click (fn [e] (swap! foo conj 1)
                        (js/console.log @foo))}])

Had foo been an actual Clojure/Script atom, then swap! would be a blocking call and @foo would get the new value.

What I am proposing is something like:

(let [foo (<-state #{})]
  [:button {:on-click (fn [e] (send-> foo conj 1)
                        (js/console.log @foo))}])

The result would be exactly the same -- @foo will still give me the pre-render value (an empty set), but now as a consumer of the API I find it less confusing, because it's not an atom -- it's just something that I can deref.

Ideally one could also attach a validator to catch invalid states but that's a second step.

mhuebert commented 5 years ago

yes - I understand the use-case; my question is, why not provide a state API such that swap! and reset! are synchronous operations, since it would appear to be a safe API to implement, with the caveat that the atom shouldn't be mutated during render.

orestis commented 5 years ago

There are subtle interplays with useEffect that Lokeh has found out. We should collect all this discussions into a single page because it’s spread out over many issues and PRs etc.

lilactown commented 5 years ago

Closing this for now.

What I've done is kept <-ref as an atom, and changed <-state to return [value set-value] tuple.

The set-value function can be used like swap! e.g. (set-value assoc :key new-value)