Comments (11)
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.
from hx.
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)))
from hx.
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.
from hx.
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?
from hx.
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.
from hx.
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.
from hx.
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.
from hx.
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.
from hx.
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.
from hx.
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.
from hx.
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)
from hx.
Related Issues (20)
- Destructuring defnc :keys [class] has weird behaviour HOT 1
- Improved react dev-tools support for hooks HOT 3
- CLJS data structures are compared by ref in <-effect deps HOT 11
- Semantics and API of <-state HOT 16
- class & className issue when wrapping defnc component with pure react component HOT 3
- Make it fast
- Experience Report HOT 7
- Reducers dont support Multimethods HOT 4
- Document hiccup parser API
- hx/f exceptions handlint HOT 4
- any HOT 1
- Export hooks under Clojure-style names HOT 2
- `defcomponent` API is very confusing HOT 1
- How-to contains misleading memo use HOT 7
- Push missing tags + maybe a 0.5.4 release HOT 2
- Docstring support for defnc (and defcomponent) HOT 1
- track dependencies to selectively rerender with useMemo HOT 3
- Passing down original js props in render props does not work with js->clj
- hx.hooks/useMemo deps as CLJS collection? HOT 1
- Typo in package 0.5.3 (maybe broken) HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from hx.