Loading

Recoil - a new state management library developed by Facebook for React

Recoil - a new state management library developed by Facebook for React

We all already heard about Redux, which has been used by many developers to manage the state of an entire JavaScript application. But recently, Facebook has launched a new state management library for React applications called Recoil. It works and thinks as same as like React does. It is assumed that Recoil is going to replace Redux.


Core Principal:

The three main principals of Recoil are flexible shared state, derived data and queries, and app-wide state observation. It helps us to create a data-flow graph that flows from a shared state called Atom through a pure function called Selector and down into the React components.

You may also like: How to update the state based on the previous state


Atoms:

Atoms are pieces of state and can be accessed or updated from any component. When an atom is updated, all the implicitly subscribed components are re-rendered.

Atoms can be created by using the following atom function:

const nameState = atom({
    key: 'UNIQUE_ID',
    default: 0,
});

Here we have to pass a unique key and a default value. It throws an error if two atoms have same key. Atom used this key for debugging and do some API calls. Recoil used useRecoilState hook to get access and update the atom from a component like useState in React.


Selectors:

Selectors are pure function that accepts atoms or other selectors as input and are used to calculate derived data that is based on state. Like atoms, when atoms or selectors are changed, the selector function will be re-evaluated and all the subscribed components will then be re-rendered.

Selectors can be created by using the selector atom function:

const nameCountState = selector({
    key: 'UNIQUE_ID',
    get: ({get}) => {
        // Atom value can be access here
        // Return your calculated value
    },
});

Installation Process:

Run the following command to download the latest stable version of Recoil package from npm:

npm:

npm install recoil

or

yarn:

yarn add recoil

You may also like: Update Meta tags dynamically for Facebook (Open graph)

How To Use:

First, create a React app by running the following command:

npx create-react-app my-app-recoil

And then install Recoil like above.

Second, to use recoil state we need to use RecoilRoot in App component because App is the root component of the application:

import {
    RecoilRoot,
    atom,
    selector,
    useRecoilState,
    useRecoilValue,
} from 'recoil';

function App() {
    return (
        <RecoilRoot>
                <CharacterCounter />
        </RecoilRoot>
    );
}

Third, create an Atom using the following command:

const nameState = atom({
    key: 'nameState',
    default: ''
});

And then create a component which is going to use the useRecoilState():

function NameCounter() {
    return (
        <div>
            <NameInput />
            <NameCount />
        </div>
    );
}

function NameInput() {
    const [name, setName] = useRecoilState(nameState);

    const onChange = (event) => {
        setName(event.target.value);
    };

    return (
        <div>
            <input type="text" value={name} onChange={onChange} />
            <br />
            Echo: {name}
        </div>
    );
}

Forth, now we are going to create a Selector with the use of selector():

const nameCountState = selector({
    key: 'nameCountState', 
    get: ({get}) => {
        const name = get(nameState);
        return name.length;
    },
});

To get the value of nameCountState we are going to use the useRecoilValue() hook:

function NameCount() {
    const count = useRecoilValue(nameCountState);

    return <>Name Count: {count}</>;
}

Finally, run it on your browser.

You may also like: Moving Car Animation Using Mapbox

Related Articles