Recoil.js

Austin vollman
2 min readJan 4, 2021

What is recoil.js?

Recoil is a state management system library for react. Similar to Redux and Mobx, recoil is a library that works with react and can fill in some holes where react can fall short. First, we must get a brief overview of what React is and what are some of its limitations that Recoil can fix.

What is React?

React is a front end library for javascript, developed by Facebook for building user interfaces. Some key characteristics of React include components, JSX, and the virtual DOM. Components make up the different sections of the web page, one component might handle a search, while another makes up a list.

Some shortcomings of React that Recoil can solve.

According to the recoil.js website, some problems with react include.

  • Component state can only be shared by pushing it up to the common ancestor, but this might include a huge tree that then needs to re-render.
  • Context can only store a single value, not an indefinite set of values each with its own consumers.
  • Both of these make it difficult to code-split the top of the tree (where the state has to live) from the leaves of the tree (where the state is used).

How does Recoil improve upon what React provides?

According to the Recoil.js website some of the things recoil allows you to do include.

  • The state definition is incremental and distributed, making code-splitting possible.
  • State can be replaced with derived data without modifying the components that use it.
  • Derived data can move between being synchronous and asynchronous without modifying the components that use it.
  • We can treat navigation as a first-class concept, even encoding state transitions in links.
  • It’s easy to persist the entire application state in a way that is backwards-compatible, so persisted states can survive application changes.

One characteristic of recoil is atoms. Atoms are units of state with an example below.

const fontSizeState = atom({

key: ‘fontSizeState’,

default: 14,

});

useRecoilState is a hook in recoil that allows you to read and write an atom from a component. The example below shows how this hook can be used to create a button to increase font size.

function FontButton() {

const [fontSize, setFontSize] = useRecoilState(fontSizeState);

return (

<button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}>

Click to Enlarge

</button>

);

}

Conclusion

These are just a few examples of how recoil works, and can make your time working with react easier. I think everyone who wants to work with react should have this library and become familiar with it.

--

--