OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Using Recoil instead of Redux For State Management In React Applications.

Origho Precious
September 16th, 2021 · 9 min read

Among all the state management libraries available for use in React apps, Redux is the most popular even ahead of React’s Context APIs. There are also other awesome state management libraries used in React apps one of which is Recoil. Recoil unlike Redux is very easy to set up, even easier to set up than the new Redux toolkit library. In this article, we will learn how to use Recoil to manage states in React apps instead of Redux.

What is Recoil?

According to documentation,

Recoil is a state management library for React applications.

Recoil is an open-source state management library with more than 14k stars on Github, it was invented by Dave McCabe, a Software Engineer at Facebook. It provides a global state so all components in a React application can share states easily and it is minimal compared to Redux with no boilerplate code setup needed.

Recoil provides a data-graph that flows from shared states into React components. The two core concepts of Recoil according to the official documentation are:

  1. Atoms, which are units of the global state provided by Recoil, components can access and subscribe to changes made to them.
  2. Selectors with which we can transform states either synchronously or asynchronously, and components can also access and subscribe to.

Why Use Recoil?

Considering that we have many other state management libraries out there and also React’s Context API and component state, why then should we use Recoil in our React apps?. Let’s highlight some of the reasons below:

  • Recoil just like Redux provides a global state. With Recoil, we won’t have to pass states as props down to children components in order to share them between components (a concept known as prop drilling).
  • Once we hook up a component to any Atom or Selector, they are subscribed to it, so any update made to that piece of state will be reflected across the app to wherever it’s being used.
  • With Recoil Selectors, we can transform a state synchronously or asynchronously and use the derived state anywhere in our app.
  • Recoil is minimal and requires no boilerplate code to get started. Redux is very popular but many developers still frown at it because of the amount of code they need to write to set it up.

Building a React App with Recoil

We have now gone over what Recoil is, its core concepts, and why you should consider using it. In this section, we will build an anime-quote-generator, this app will fetch quotes from an external API based on selected animes.

Let’s get started by generating a new React app with the command below.

1npx create-react-app anime-quote-generator

After that, open it in your favorite code editor.

Next, we will install Recoil and get started building our app components. Run the command below to install Recoil.

1yarn add recoil

OR

1npm install recoil

Let’s configure our app to use Recoil. Navigate to src/index.js, here, we only need to wrap our entire app with RecoilRoot; a Recoil component. Let’s do that below.

1import React from "react";
2import ReactDOM from "react-dom";
3import { RecoilRoot } from "recoil";
4import "./index.css";
5import App from "./App";
6
7ReactDOM.render(
8 <RecoilRoot>
9 <App />
10 </RecoilRoot>,
11 document.getElementById("root")
12);

We have successfully set up Recoil in our React app just by wrapping all our app’s components with it. You see how easy the setup is, to do this using Redux we will have to write some lines of code to create a store before wrapping our app with the React-Redux Provider component that will contain the store.

Now that we have set up Recoil in our app, let’s start building components, pages, and sharing states with Recoil.

Building AnimePill Component

This component will render the title of an anime passed to it, and when clicked, it will route us to a page where we’ll see quotes from that anime. First, we need to install react-router-dom for routing between pages in our app and styled-components for styling. Let’s do that with the command below:

1yarn add react-router-dom styled-components

OR

1npm install react-router-dom styled-components

Next, let’s create a folder in the src folder, called components. In the components folder, create a folder called AnimePills and a file called AnimePills.jsx inside that folder. The path to this file from src should be src/components/AnimePills/AnimePills.jsx, now add the code below to that file.

1import { Link } from "react-router-dom";
2import styled from "styled-components";
3
4const AnimePill = ({ anime, color }) => {
5 return (
6 <StyledPill style={{ background: color }}>
7 <Link to={`/anime/${anime}`}>{anime}</Link>
8 </StyledPill>
9 );
10};
11
12const StyledPill = styled.div`
13 border-radius: 999px;
14 & a {
15 display: block;
16 text-decoration: none;
17 color: #333;
18 padding: 1rem 2rem;
19 }
20`;
21
22export default AnimePill;

Above, we just created a component called AnimePills. This component takes in 2 props; anime and color, with the anime we will construct a link using the Link component from react-router-dom and we will use the color as a background-color. We then style the component with styled-components.

Building Quote and SmallQuote components

We will be building 2 components in this section. Let’s start with the Quote component. Inside our components folder, create a new folder called Quote and a file Quote.jsx inside it. In this component, we will simply render a quote from Naruto and style the component with styled-components. Add the code below to the file.

1import styled from "styled-components";
2
3const Quote = () => {
4 const quote = {
5 anime: "Naruto",
6 character: "Pain",
7 quote:
8 "Because of the existence of love - sacrifice is born. As well as hate. Then one comprehends... one knows PAIN.",
9 };
10
11 return (
12 <StyledQuote>
13 <p>"{quote.quote}"</p>
14 <h4>
15 <span className="character">{quote.character}</span> <em>in</em>{" "}
16 <span className="anime">{quote.anime}</span>
17 </h4>
18 </StyledQuote>
19 );
20};
21
22const StyledQuote = styled.div`
23 background: #dbece5;
24 padding: 3rem 5rem;
25 display: flex;
26 flex-direction: column;
27 align-items: center;
28 & > p {
29 font-size: 2rem;
30 letter-spacing: 2px;
31 text-align: center;
32 font-style: italic;
33 margin-bottom: 3rem;
34 background: #fff;
35 border-radius: 0.5rem;
36 padding: 3rem;
37 }
38 & > h4 {
39 font-size: 1.5rem;
40 font-weight: 500;
41 letter-spacing: 2px;
42 span {
43 padding: 5px 10px;
44 }
45 em {
46 font-size: 1.2rem;
47 }
48 & > .character {
49 background: #b8dace;
50 }
51 & > .anime {
52 background: #f5e7e4;
53 }
54 }
55`;
56
57export default Quote;

Next, let’s create the SmallQuote component. This component expects 3 props (anime, character and quote), we will render these props, and style the component with styled-components. To do this, create a folder inside src/components called SmallQuote, inside it create a file SmallQuote.jsx and add the code below

1import styled from "styled-components";
2
3const SmallQuote = ({ quote, character, anime }) => {
4 return (
5 <StyledQuote>
6 <p>"{quote}"</p>
7 <h4>
8 <span className="character">{character}</span> <em>in</em>
9 <span className="anime">{anime}</span>
10 </h4>
11 </StyledQuote>
12 );
13};
14
15const StyledQuote = styled.div`
16 background: #dbece5;
17 padding: 1.5rem 2.5rem;
18 display: flex;
19 flex-direction: column;
20 align-items: center;
21 & > p {
22 font-size: 1rem;
23 letter-spacing: 2px;
24 text-align: center;
25 font-style: italic;
26 background: #fff;
27 border-radius: 0.5rem;
28 padding: 1.5rem;
29 margin-bottom: 1.5rem;
30 }
31 & > h4 {
32 font-size: 1rem;
33 font-weight: 500;
34 letter-spacing: 2px;
35 span {
36 padding: 3px 5px;
37 }
38 em {
39 font-size: 1rem;
40 }
41 & > .character {
42 background: #b8dace;
43 }
44 & > .anime {
45 background: #f5e7e4;
46 }
47 }
48`;
49
50export default SmallQuote;

Above, we just built a component called SmallQuote and styled it with styled-components. It is very similar to Quote component, the purpose of splitting them is to make the code easier to understand. So if you want to make the Quote component reusable to include features of the SmallQuote component, feel free to do that.

Next, we will be building our app atoms and selector.

Building Our App Global State (Atoms and Selector).

To get started, navigate into our src folder and create a folder called store, inside this folder create a file called index.js. In this file, we will build all the atoms we need and also a selector to modify one of the atoms. Let’s start with the first atom, animeTitles. Add the code below to create our first atom.

1import { atom } from "recoil";
2
3export const animeTitles = atom({
4 key: "animeTitleList",
5 default: [],
6});

Above, we created an Atom by importing atom from recoil and called it “animeTitles. We then defined the required properties of an atom, which are

  • key - this should be a unique ID among other atoms and selectors we will create in the app.
  • default - this is the default value of the atom.

Doing this with Redux, we will have to create an action creator with a specific type, the action creator will return the type and a payload passed to it, and also we will create a reducer to update our redux store. but with Recoil we don’t need to handle all of that, with the key prop, Recoil knows the part of the global state to update so when we pass data to update the state it does it correctly and we won’t need to compare action types as we would do in Redux.

Following the same pattern, let’s create another atom called animePageNum. we will use this atom to hold page number, this will help us properly handle pagination in this app. Add the code below to this file.

1export const animeListPageNum = atom({
2 key: "animeListPageNum",
3 default: 0,
4});

Next let’s create a selector to mutate the array of data we will have in the animeTitles atom by slicing the array to return only 50 items at a time based on the page number which we will get from animePageNum atom.

1export const slicedAnimeTitles = selector({
2 key: "slicedAnimeTitles",
3 get: ({ get }) => {
4 const animes = get(animeTitles);
5 const pageNum = get(animeListPageNum);
6
7 const newAnimeList = [...animes];
8 const arrIndex = pageNum === 0 ? 0 : pageNum * 50 + 1;
9
10 return newAnimeList.splice(arrIndex, 50);
11 },
12});

Above, we created a selector called slicedAnimeTitles, we defined a key property just like we did in the atoms we created above, and here we have a new property get whose value is a function, this is only available in selectors, this function has 2 parameters but here we are using just one of them that is get with which we can access the value of an atom or selector. Inside this function, with the get method, we saved the animeTitles and animeListPageNum atoms into 2 variables animes and pageNum respectively, and with the pageNum we specified the index to start slicing from and then returned a new array of just 50 items.

We have now successfully created all the shared states we will be using in this app. Next. Let’s create a pagination component, to handle user click and update the animeListPageNum state (atom) so we can update the list of animes we are returning from the selector we just created.

Building Pagination Component

To begin, navigate to src/components and create a new folder Pagination, inside it create a file Pagination.jsx, paste the code below into this file.

1import { useState, useEffect } from "react";
2import { useRecoilState } from "recoil";
3import styled from "styled-components";
4import { animeListPageNum } from "../../store";
5
6const Pagination = ({ listLength }) => {
7 const [pageNum, setPageNum] = useRecoilState(animeListPageNum);
8 const [numsArr, setNumsArr] = useState([]);

Above, we created a new component Pagination. This component has a prop listLength; this will help us determine the page numbers to render. We then imported [useRecoilState](https://recoiljs.org/docs/api-reference/core/useRecoilState), which accepts a state as an argument just like React’s useState hook, This also works similar to useSelector in Redux But here we can update the state directly and not have to dispatch an action. We can access the value of the state passed to useRecoilState and also update the state, We also created a component state with useState hook to hold an array of numbers, these will be the page numbers to render in this component.

1useEffect(() => {
2 const paginationNums = () => {
3 const max = Math.floor(listLength / 50);
4 let nums = [];
5 for (let i = 0; i <= max; i++) {
6 nums.push(max - i);
7 }
8 setNumsArr(
9 nums.sort((a, b) => {
10 return a - b;
11 })
12 );
13 };
14 paginationNums();
15 }, [listLength]);
16
17 return (
18 <StyledPagination>
19 {numsArr?.length
20 ? numsArr?.map((num) => (
21 <button
22 className={pageNum === num ? "active" : ""}
23 onClick={() => setPageNum(num)}
24 key={num}
25 >
26 {num + 1}
27 </button>
28 ))
29 : null}
30 </StyledPagination>
31 );
32};

In the useEffect we imported above, we created an array of numbers with the listLength prop, and updated the numArr state with the array we created and then we looped through the array of nums and rendered them in buttons, each button will update the animeListPageNum when clicked. Let’s complete this component by adding the code below.

1const StyledPagination = styled.div`
2 display: flex;
3 align-items: center;
4 border-width: 2px 2px 2px 0;
5 border-style: solid;
6 width: max-content;
7 & button {
8 outline: none;
9 background: transparent;
10 border: none;
11 border-left: 2px solid;
12 width: 35px;
13 height: 30px;
14 display: flex;
15 align-items: center;
16 justify-content: center;
17 &:hover,
18 &.active {
19 background: #fae1da;
20 }
21 }
22`;
23
24export default Pagination;

With the Pagination component done, we can now build our app pages and complete the app.

Building Homepage Component

In this section, we will build our homepage component, this page will render a static quote and also a list of animes using the AnimePill component we created earlier and also the Pagination component for pagination. To do this, in our src folder let’s create a folder called pages, in this folder create a folder called home and a file inside it called index.jsx, folder path should src/pages/home/index.jsx. Add the code below to this file

1import { useRecoilValue } from "recoil";
2import styled from "styled-components";
3import AnimePill from "../../components/AnimePill/AnimePill";
4import Pagination from "../../components/Pagination/Pagination";
5import Quote from "../../components/Quote/Quote";
6import { slicedAnimeTitles, animeTitles } from "../../store";
7
8const Homepage = () => {
9 const animes = useRecoilValue(animeTitles);
10 const slicedAnimes = useRecoilValue(slicedAnimeTitles);
11 const colors = ["#FAE1DA", "#E8C6AD", "#F2E2ED", "#D6EBE4", "#BFDCD0"];
12
13 const generateColor = () => {
14 const randNum = Math.floor(Math.random() * 5);
15 return colors[randNum];
16 };
17
18 return (
19 <StyledHomePage>
20 <header>
21 <h2>Anime Quote Generator</h2>
22 </header>
23 <main>
24 <Quote />
25 <div className="animes">
26 <h3>All Animes</h3>
27 {animes?.length ? (
28 <p>Click on any anime to see a quote from it</p>
29 ) : null}
30 <div className="flex">
31 {animes?.length ? (
32 slicedAnimes?.map((anime) => (
33 <div key={anime} style={{ margin: "0 1.3rem 1.3rem 0" }}>
34 <AnimePill anime={anime} color={generateColor()} />
35 </div>
36 ))
37 ) : (
38 <p className="nodata">No anime found 😞 </p>
39 )}
40 </div>
41 {animes?.length > 50 ? (
42 <div className="pagination">
43 <Pagination listLength={animes?.length} />
44 </div>
45 ) : null}
46 </div>
47 </main>
48 </StyledHomePage>
49 );
50};
51
52const StyledHomePage = styled.div`
53 max-width: 80%;
54 margin: 2rem auto;
55 & header {
56 margin-bottom: 3rem;
57 & > h2 {
58 font-weight: 400;
59 letter-spacing: 3px;
60 text-align: center;
61 }
62 }
63 & .animes {
64 margin-top: 4rem;
65 & > h3 {
66 font-weight: 400;
67 font-size: 1.4rem;
68 background: #ece4f1;
69 width: max-content;
70 padding: 0.3rem 1rem;
71 }
72 & > p {
73 margin: 1.2rem 0;
74 }
75 & > .flex {
76 display: flex;
77 justify-content: center;
78 flex-wrap: wrap;
79 & > .nodata {
80 margin: 2rem 0 4rem;
81 font-size: 1.3rem;
82 }
83 }
84 & .pagination {
85 display: flex;
86 flex-direction: column;
87 align-items: center;
88 margin: 2rem 0 4rem;
89 }
90 }
91`;
92
93export default Homepage;

Above, we imported:

  • useRecoilValue from the Recoil library to get the state values,
  • styled from styled-components to style the Homepage component,
  • AnimePill to render anime title,
  • Pagination to handle pagination,
  • Quote to display a static anime quote,
  • SlicedAnimeTitles is the selector we created earlier. We will be its return value on this page, and
  • animeTitles which is the first atom we created to hold the list of animes.

Next, we created a function component called Homepage inside this component, we accessed the animeTitles and the slicedAnimeTitles state using useRecoilvalue and also we created an array of colors (we will pass these colors to the AnimePill component at random). We then created a function generateColor, this component returns a random color from the colors array. After that, we returned the component body styled with styled-components, a header, the Quote component, and a little notice telling a user what to do, then if we have animes, we will loop through the slicedAnimes and render each of them with the AnimePill component by passing the anime to the component and also a color prop from the generateColor function and if there’s none we render a ‘no data’ state.
Next, we are checking to see if the length of the animes state is more than 50, if true we render the Pagination component. and finally, we added a block of styled-component styles

We’ve now successfully created our Homepage component, in the next section let’s create a page we will be routed to when we click on any AnimePill. In that component, we will make an API call to the external API and fetch all quotes from the selected anime and render the quotes.

Building Animepage Component

Let’s get started by navigating to our pages folder, inside create a folder called anime and a file inside it called index.jsx. Add the code below to the file.

1import { useState, useEffect } from "react";
2import { Link, useParams } from "react-router-dom";
3import axios from "axios";
4import styled from "styled-components";
5import SmallQuote from "../../components/SmallQuote/SmallQuote";
6
7const Animepage = () => {
8 const param = useParams();
9 const [quotes, setQuotes] = useState([]);
10 const [loading, setLoading] = useState(false);
11
12 useEffect(() => {
13 if (param?.name) {
14 setLoading(true);
15 const fetchAnimeQuotes = async () => {
16 try {
17 const res = await axios.get(
18 `https://animechan.vercel.app/api/quotes/anime?title=${param?.name}`
19 );
20 setQuotes(res?.data);
21 setLoading(false);
22 } catch (error) {
23 console.log(error);
24 setLoading(false);
25 }
26 };
27 fetchAnimeQuotes();
28 }
29 }, [param]);
30
31 return (
32 <StyledAnimePage>
33 <h2>Quotes from {param?.name}</h2>
34 <Link to="/">Go back</Link>
35 <div className="grid">
36 {loading ? (
37 <p>Loading...</p>
38 ) : quotes?.length ? (
39 quotes?.map((quote, index) => (
40 <div key={quote?.quote + index} className="anime">
41 <SmallQuote
42 anime={quote?.anime}
43 character={quote?.character}
44 quote={quote?.quote}
45 />
46 </div>
47 ))
48 ) : (
49 <p className="nodata">No Quote found 😞</p>
50 )}
51 </div>
52 </StyledAnimePage>
53 );
54};
55
56const StyledAnimePage = styled.div`
57 max-width: 80%;
58 margin: 2rem auto;
59 position: relative;
60 & > a {
61 position: absolute;
62 top: 1rem;
63 text-decoration: none;
64 }
65 & > h2 {
66 font-weight: 400;
67 letter-spacing: 3px;
68 text-align: center;
69 margin-bottom: 2rem;
70 }
71 & > .grid {
72 display: grid;
73 grid-template-columns: repeat(2, 1fr);
74 grid-template-rows: max-content;
75 & .anime {
76 margin: 1rem;
77 height: max-content;
78 }
79 & > p {
80 margin: 2rem 0 4rem;
81 font-size: 1.3rem;
82 text-align: center;
83 }
84 }
85`;
86export default Animepage;

Above, we imported all the components and hooks we will be using. We also initialized the [useParams](https://reactrouter.com/web/api/Hooks/useparams.) hook, to get an anime title from our browser URL as a param based on the route we’ll define for this page. Next, we created 2 component states using useState hook, one to hold the quotes we will fetch from the API and the other for a loading, And in a useEffect, we are fetching the quotes based on the anime name gotten from the URL and setting the quotes state with it. We then returned a block of jsx styled with styled-components.

Above, you’ll notice that we didn’t use Recoil, instead, we saved the response we got from the API request in a useState, this is because the states will only be used in this component.

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Creating App Routes and Fetching Animes

To complete this app, Let’s navigate to src/App.js. Here, we will be doing 2 things:

  1. Fetch a list of animes from the external API and updating the animeTitles atom we created earlier with it.
  2. Define our app routes with react-router-dom.

Let’s get started. Go to src/App.js and replace what we have there with the code below.

1import { useEffect } from "react";
2import { BrowserRouter, Route, Switch } from "react-router-dom";
3import { useSetRecoilState } from "recoil";
4import axios from "axios";
5import { animeTitles } from "./store";
6import Homepage from "./pages/home";
7import Animepage from "./pages/anime";

Above, We imported

  • useEffect - We will be making our API call inside it, so that we can fetch the array of anime once the page is rendered.
  • BrowserRouter, Route, and Switch from react-router-dom - We will create our routes with them.
  • [useSetRecoilState](https://recoiljs.org/docs/api-reference/core/useSetRecoilState) from recoil - with this, we will update the animeTitles atom just by passing the atom to it as an argument, and
  • axios - for fetching data from the external API

Next, we will create the App component and fetch the animes inside. To do that add the code below.

1const App = () => {
2 const setTitles = useSetRecoilState(animeTitles);
3
4 const fetchAnimes = async () => {
5 try {
6 const res = await axios.get(
7 "https://animechan.vercel.app/api/available/anime"
8 );
9 setTitles(res?.data);
10 } catch (error) {
11 console.log(error?.response?.data?.error);
12 }
13 };
14
15 useEffect(() => {
16 fetchAnimes();
17 }, []);

Above, we created the App component, and inside we created a variable setTitles with which we will update our animeTitles atom (state). Next, we created an async function called fetchAnimes, inside it, we fetched the animes from the external API using axios and updated our animeTitles state with it while using try-catch for error handling. After that we called the fetchAnimes inside the useEffect we imported so this function runs once the page is rendered.

Let’s finish up the App component by adding routes.

1return (
2 <BrowserRouter>
3 <Switch>
4 <Route exact path="/" component={Homepage} />
5 <Route exact path="/anime/:name" component={Animepage} />
6 </Switch>
7 </BrowserRouter>
8 );
9};
10
11export default App;

We have now completed our app. let’s start our dev server to see how it works. Run the command below in your terminal

1yarn start

OR

1npm start

If you followed along correctly, you should see these pages.

localhost:3000 - homepage

Click on any anime and see a page like this. I will click on Naruto.

anime page showing quotes from Naruto

Conclusion

In this article, we learned what Recoil is, why use it, and how to use it instead of Redux by building an anime-quote-generator app using Recoil for state management. We also compared how to do certain things in Recoil to Redux, and we saw how easy it is to use Recoil. You can learn more about Recoil from the official docs.

Resources

More articles from OpenReplay Blog

Infinite Scrolling in Vue using the Vue Intersection Observer API

Finding ways of rendering lots of information can hinder the performance of your Webapp, using infinite scrolling is a technique to solve this problem.

September 15th, 2021 · 4 min read

Forever Functional: Higher Order Functions -- Functions to rule functions

Using functions to alter the way other functions work, take a closer look at the power of Higher Order Functions in JavaScript

September 13th, 2021 · 6 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552