3
6 Comments

Getting started with Recoil - Facebook State Management Library for React

What is RecoilJS?

RecoilJS is a state management library for React apps.

Highlights

  • Thinks like React and flexible with shared state;
  • Pure functions and efficient subscriptions;
  • Comes with persistence, routing, time-travel debugging;

Concepts

Atoms

Atoms are units of state and can be created at runtime. Atoms can be used in place of React local component state. If the same atom is used from multiple components, all those components share their state.

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

Selectors

A selector is a pure function that accepts atoms or other selectors as input. When these upstream atoms or selectors are updated, the selector function will be re-evaluated.

const fontSizeLabelState = selector({
  key: 'fontSizeLabelState',
  get: ({get}) => {
    const fontSize = get(fontSizeState);
    const unit = 'px';

    return `${fontSize}${unit}`;
  },
});

 

The Counter is the new Hello World

Yesterday I was trying out the new Facebook state library and I ended up making a Codesandbox with a simple counter trying out all the features.

RecoilRoot

It provides the context in which atoms have values. Must be an ancestor of any component that uses any Recoil hooks.

import React from "react";
import { RecoilRoot } from "recoil";

export default function App() {
  return (
    <RecoilRoot>
      <h1>Recoil counter</h1>
      <Counter />
      <CounterInfo />
    </RecoilRoot>
  );
}

Atom

Atoms need a unique key, which is used for debugging, persistence, and for certain advanced APIs that let you see a map of all atoms. It is an error for two atoms to have the same key, so make sure they're globally unique. Like the React component state, they also have a default value.

import { atom } from "recoil";

const countState = atom({
  key: "countState",
  default: 0
});

Selector

Selectors are used to calculating derived data that is based on state. Since selectors keep track of what components need them and what state they depend on, they make this functional approach more efficient.

import { selectoratom } from "recoil";

const countNextState = selector({
  key: "counterNextState",
  get: ({ get }) => {
    return get(countState) + 1;
  }
});

useRecoilState

Returns a tuple where the first element is the value of state and the second element is a setter function that will update the value of the given state when called.

import React from "react";
import { useRecoilState } from "recoil";

const Counter = () => {
  const [count, setCount] = useRecoilState(countState);
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};

useRecoilValue

Returns the value of the given Recoil state. This hook will implicitly subscribe to the component to the given state. This component shares the same atom making the count state global.

import React from "react";
import { useRecoilValue } from "recoil";

const CounterInfo = () => {
  const count = useRecoilValue(countNextState);
  return <p>the next number is {count}</p>;
};

Counter Demo using Recoil

https://codesandbox.io/embed/recoil-counter-demo-b0ghg?fontsize=14&hidenavigation=1&theme=dark

What is UpStamps?

UpStamps is a Feature Flag Management Platform to separate code from different environments and projects.

UpStamps helps teams manage their projects using feature management with a Central control to progressively deliver features to users with confidence.

Sign Up for Free

🛳 Ship when you're ready
🚀 Accelerate feature release
🙈 Hide unfinished features

UpStamps Control Center

Useful links about UpStamps:

on May 17, 2020
    1. 1

      Yes, Kea is really god, I like the way is organized by logics and is very opinionated. The latest version supports hooks that's awesome.

      As Recoil came out recently I wanted to experiment by doing something simple. Please note that Recoil is in experiment mode, I think it is not yet recommended for production use. One of the things I like about Recoil is that it makes it look like it’s part of the React library

  1. 1

    How does Recoil compare to Redux?

    Seems like there's less boilerplate (mapStateToProps, mapDispatchToProps, etc.) but Redux to me is a clear central store of information in the app. Does Recoil work the same way?

    Also I read before that Redux tried switching to React.Context and it was too slow, so they reverted, but this seems like it's using context?

    Thanks!

    1. 1

      RecoilJS uses the Context API internally and it solves the problem of efficient render with shared state across components. This is a problem React (Context) and most state management libraries don't solve properly.

      Recoil builds on React primitives, the benefits are clear: Cleaner and more compatible with concurrent mode. It is like having useState on steroids.

      In my opinion, I feel like Recoil is part of the React core facilitating the use of state or shared state in your components with less context boilerplate.

      This may not answer your question and it is too early to compare the two. Recoil is still experimenting but gaining a lot of hype.

  2. 1

    Real dumb question: what problem is Recoil supposed to solve ? Why should I use it?

    1. 1

      The core concept of Recoil is the data-flow where data travels from Atoms (shared state) through Selectors (pure functions) down into React components building your app.

      React Components can subscribe to these atoms. The subscription can be used to get and set data from Atoms. Recoil works and thinks just like React providing a fast & flexible shared state.

      Advantages:

      • Easy to set up and use
      • Supports asynchronous state management
      • State persistence
      • boilerplate-free API where the shared state has the same simple get/set interface as React local state;
      • Compatibility with Concurrent Mode and other new React features as they become available;
      • Code-splitting possibility thanks to incremental & distributed state definition,
      • The state can be replaced without modifying the components that use it.
      • Derived data can move between being synchronous and asynchronous without modifying the components that use it.
      • Backward-compatibility of application state; persisted states can survive application changes.