top | item 23183355

(no title)

mmerickel | 5 years ago

Is there any support for changing multiple atoms at once / batch? This is where reducers shine to me - dispatching a single action from the ui in redux that multiple reducers can listen to and use to update their state.

Also is there any support for getting the values of atoms outside of a hook? For example from an async action that is not coupled to the render loop which also wants to know the current value.

discuss

order

davidmccabe|5 years ago

If you update multiple atoms within a React batch, they will be updated at the same time, just as with React local state. You don't need to wrap the changes in anything to have them occur together.

In other words, this updates both of the atoms together:

  const [a, setA] = useRecoilState(atomA);
  const [b, setB] = useRecoilState(atomB);
  ...
  onClick={() => {
    setA(a => a + 1);
    setB(b => b + 1);
  }}

If the new values of multiple atoms are interdependent on each others' current values, it's possible to update multiple atoms together using the transactional/updater/function form, but we need to add a nicer interface for doing this. Coming soon! The nicer interface would probably look something like this:

  const update = useTransactionalUpdate([atomA, atomB]);
  ...
  onClick={() => {
    update(([a, b]) => [a + b, b - a]);
  }}
It's then easy to make a hook that provides a reducer-style interface over a set of atoms. But now, unlike with Redux or useReducer, each atom still has its own individual subscriptions!

mmerickel|5 years ago

It seems like something could be written around useRecoilCallback() to watch/get the current value of an atom outside of a React component. Does that sound right?