Recoil is a new state management library for React that lets you manage global/sharable state in a Reactish way. What’s great is that Recoil is being developed by the Facebook team. In this blog we’ll take a look at the useRecoilState hook and how they have made it is so ‘React’-ish?
Let’s take a very simple problem statement.
We want to share the count state variable within two siblings/parallel children components.
First Solution: Prop-Drilling
The simplest possible solution would be moving count to a common parent and passing it down through props.
This solves our problem but it will lead to below issues
- Here we have a simple level tree, but what if we have more, say 4 or 5 levels? Prop drilling through so many levels will make the code difficult to navigate
- The entire component tree will rerender – rather than just the 2 leaf components.
- The parent component will be overloaded with state and might lead to unnecessary re-renders.
Second Solution: Context API
We can make use of the context API from React. Context provides a way to pass data through the component tree without having to manually pass it down at every level.
We need to wrap the parent component within a Context.Provider and the child components (C1&C2) can subscribe to it using the useContext hook. This helps us avoid prop-drilling. However, there are a few limitations to using this approach:
- Need for multiple context providers — A Context.Provider can only share a single value, not an indefinite set of values – each with its own consumers.
- Complex unit test cases — Need to create a mock provider to write unit test cases.
- We will still be re-rendering every component in the tree when the context changes. (This is why redux was needed even though context could manage global state without prop drilling)
Third Solution: useRecoilState
Finally I will introduce useRecoilState, where we can easily achieve this by creating a shareable subscriber unit of state using atoms. To take benefits of the Recoil API we need to wrap the parent component in RecoilRoot.
Let’s look at why Recoil is said to be ‘Reactish’ and ‘Minimal’.
I am comparing useState and useRecoilState just to show how similar the syntax is. But, the functionality of Recoil can be compared with other global state management libraries like Redux, MobX, Apollo GraphQL etc.
Conclusion : Recoil is still in its experimental phase, but it is progressing quickly.
More reading :