Updating an atom outside of useAtom hook
See original GitHub issueI believe the answer is probably going to be similar to #454, but worth checking 😃
I am trying to update an atom outside of a component. For instance that can be in a handleClick
function that is outside of a component to be reused between multiple components.
const handleClick = () => {
setAtom(myAtom, 'value') // <-- I want to do something like that
}
const ButtonA = () => <button onClick={handleClick} />
const ButtonB = () => <button onClick={handleClick} />
Is there any way to do this? If not, could this become possible in the future, or is there any workaround? Thank you.
As a side note, it is not possible in Recoil either.
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
How to update atoms (state) in Recoil.js outside components ...
The problem is since these functions are not defined inside components I can't use recoil hooks (like useRecoilState to access selectors/atoms).
Read more >useUpdateAtom - Jotai
For newer versions of Jotai you can also use useSetAtom instead. import { atom, useAtom } from 'jotai'. import { useUpdateAtom } from...
Read more >Simple atomic state that can be updated outside of React components
Simple atomic state that can be updated outside of React components ... and setter function with 'useAtom' hook const [user, setUser] = useAtom(userAtom); ......
Read more >Looking at Jotai, an Awesome State Management for React
One can build state by combining atoms and renders are optimized based ... If you want to update state outside React, Zustand works...
Read more >Atom Effects | Recoil
Also check out the recoil-sync library for some implementations of syncing (such as ... The Snapshot hooks API can also monitor atom state...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Good point, thank you for the explanation. My codebase is not at a point where I can easily go back to test the issue in Jotai. I’ve switched to Zustand with no commit in between. We can close the issue, thank you very much for the quick answers 😃
A workaround would be to use module state. We have two-way bindings. And, we have three options:
jotai/valtio
,jotai/zustand
, andjotai/redux
. (Hoping this comment doesn’t confuse you.)But, for your use case described in the first comment, it’s not recommended.