Recoil.js the state management library for React

Recoil.js is a state management library for React.js. Dave McCabe and his friends invented the Recoil.js library to extend the limitations hit while managing global state. It offers React-like API and it is helpful to handle global, asynchronous and derived states. If you know React.js using Reacoil will be pretty easy for you. Let’s see an example.

In our example we are using React with useState() to increment a number.


// React and setState


const Counter = () => {

  const [count, setCount] = useState(0);


  return (

    <>

      <span>Count: {count}</span>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </>

  );

};


In the Recoil example to increment the number instead of useState with useRecoilState.


//React and Recoil


const Counter = () => {

  const [count, setCount] = useRecoilState(myGlobalCounterState);


  return (

    <>

      <span>Count: {count}</span>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </>

  );

};


Compared to other state libraries, Recoil.js is much more powerful. It is made to be used with React.js applications. It is compatible with React Concurrent mode, React Suspense. Other state libraries like Redux are complicated and difficult to understand. You can use its API by wrapping your code with RecoilRoot. It offers flexibility with features like selectors and the concept of atoms.