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.55k stars 1.18k forks source link

Create atom from Redux store #125

Open jamiewinder opened 4 years ago

jamiewinder commented 4 years ago

I'm currently using Redux for my application state, and Recoil looks appealing due to being able to have multiple atoms rather than a single one.

Since a Redux store is basically an example of an atom (if I'm understanding correctly), is there any way for me to create an atom from a Redux store or a similar 'subscribable' / 'observable' value? i.e. a low-level way of creating an atom with customised behaviour. It seems like it may be a good bridge for users to Recoil.

khpatel4991 commented 4 years ago

Why overcomplicate?

Use either redux or recoil to manage state.

acutmore commented 4 years ago

Hi @jamiewinder.

Yes you can think of Redux like a single Atom, one difference is that Redux can be ran and accessed outside of the React app. Recoil, on the other hand, is coupled to React.

One of the key benefits to Recoil are the performance gains possible by breaking up state into smaller isolated atoms/selectors. Redux stores tends to be one large composition of state so bringing it into Recoil does not have many benefits.

If you just want to give it a go something like this should work:

const myAtom = Recoi.atom({
    id: 'myAtom',
    default: null
});

function App() {
    const set = Recoil.useSetRecoilState(myAtom);

    React.useEffect(() => {
        set(store.getState());
        const dispose = store.subscribe(() => set(store.getState()));
        return () => dispose();
    }, []);

    return ...;
}

function ComponentB() {
    const value = Recoil.useRecoilValue(myAtom);

    return ...;
}
monteslu commented 4 years ago

Is there any way to de-couple the presentation from the logic?

The decoupling is my favorite part of redux. My least favorite part is having to use connect() with class-based components.

Perhaps methods on the atoms to update, or another read/write helper that can be used outside of the functional components?