facebookexperimental / Recoil

Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
https://recoiljs.org/
MIT License
19.59k stars 1.18k forks source link

Question: changing recoil state outside of components #179

Open Cadrach opened 4 years ago

Cadrach commented 4 years ago

Hi,

First, thanks your great work!

I have a question about the best way (or even is it possible?) to change the state of atoms outside of the components.

In mobx there are "actions" that exists to do this, and which allow to have some business logic outside of components.

How should I go about this in Recoil? I imagine I could have a basic function to which I must pass every time the atom setter, but is there a way to have a method directly available on the atom itself?

drarmstr commented 4 years ago

Recoil does not have "global" state. Its store is coupled with the current React rendering tree. This will allow it to be compatible with the new Concurrent Mode with React. That does mean that we need to use hooks to access the state. That said, you can still use a hook to construct a callback that can allow you to update the state from an async action. Check out the the useRecoilCallback() hook. Perhaps this will work for your needs?