Why can I not read / write state (atom) values from functions directly? #1422
Replies: 3 comments 20 replies
-
Thanks for opening a discussion. Jotai is based on React Context. A context is contextual and we only know where to access in a component. It's not accessible outside. Now, from your description, it seems you are not using the capability of context and it's fine. Many use cases don't require context and you are not alone. That's why Jotai provides the provider-less mode, which eases the non-context use cases. It also has unstable_createStore feature which allows you to access the store outside components. It's fairly stable but we would like to get more feedback before finalizing it. Hope it helps. |
Beta Was this translation helpful? Give feedback.
-
So, why do you want to read/write atoms outside components/hooks? |
Beta Was this translation helpful? Give feedback.
-
An example from the real world of how this can be useful: I have a suite of helper functions (technically it is a service model, but we can say helper functions) that represents an action that spans over many atoms. My app is a time tracker, and a good example is what happens when the user presses a stop button on the currently tracked entry.
The problem here is that the code that invokes the actions does not have anything to do with records (i.e. it is a timer stop button), but it would require importing the records action to proceed. In addition to that, it would be necessary to pass the I suggest
In both cases we can capture the whatever store it currently utilized by react via a hook, so we don't loose the notion of the context-based state. |
Beta Was this translation helpful? Give feedback.
-
I've been evaluating different state libraries for React. I prefer Jotai over Valtio as it mimics
useState
instead of using side effects from Proxies. What's maddening, however, is that Jotai state cannot be used from utility functions, and I don't understand this. Why? Why not create a vanilla state library that has React effects (like Valtio does) instead of making React / components an implicit dependency? Why are these state values not readable / writeable? It's super-frustrating because there are lots of use cases for setting / reading state outside of React components, even within a React app. (Such as setting a global state for a set of utility functions.)How hard would it be to add this functionality?
Beta Was this translation helpful? Give feedback.
All reactions