OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Easy-Peasy State Management Using React Easy Peasy

Fortune Ikechi
July 11th, 2021 · 11 min read

In building React applications, one of the most important questions for developers include managing state effectively. In this tutorial, we are going to learn how to use Easy Peasy for managing state in React applications. We’ll understand the core concepts of Easy Peasy, some use cases for it, why it should be used for your next application and build a simple example. Easy Peasy is open source with more than 4.1k stars on GitHub.

This tutorial will be beneficial to readers who are interested in learning how to manage state with Easy Peasy in their React applications, or looking for alternatives in regards to state management in a React application. This article requires a basic understanding of React and JavaScript.

What is Easy Peasy?

Easy Peasy is a state manager that works similar to Redux but with less code and complexity than Redux. Easy Peasy was built with the objective of providing the same performance as Redux and other state managers.

Core concepts of Easy Peasy include the following hooks and methods.

  • Store: Similar to Redux, Easy Peasy requires a store powered by React Context, which will disclose the application state to certains parts of your logic.
  • State: This is an essential part of Easy Peasy because it uses the state or model to define your application store.
  • Thunk Action: This is used in Easy Peasy to perform operations that are termed side effects, such as making an API call.
  • Actions: Actions are used to update the application store.
  • useStoreState: This is a custom hook from Easy Peasy that gives our components access to the application’s store state.
  • useStoreActions: Like the name implies, this hook gives our components access to the store’s actions.
  • Provider: Similar to Redux, Easy Peasy comes with a Provider method that exposes the store to our React app, this is done so our components will be able to consume the store with React hooks.

Easy Peasy can be installed using any package manager such as NPM by using the command below

1npm install easy-peasy

Or this command for yarn package manager

1yarn add easy-peasy

Why Easy Peasy?

Easy Peasy’s main objective is to improve state management for React developers and make for an easier way of managing application state with less code and boilerplate. Easy Peasy removes the abstractions of Redux and simplifies state management with a simpler process, making it easier for anyone to use in React applications.

Easy Peasy also provides support for React Hooks based API and Redux middlewares such as Redux thunk out of the box. With this, Easy Peasy can be setup to perform API requests as side effect using thunk actions. Let’s see the API call below for an example of a request that deletes a user and gets a user by their id.

1import { action, computed, createContextStore, thunk } from 'easy-peasy';
2import { getUserById } from './user';
3
4const UserStore = createContextStore({
5 getUsers: thunk(async actions => {
6 actions.setIsLoading();
7 try {
8 const { data } = await getUsers();
9 actions.setUsers(data);
10 } catch (e) {
11 actions.setError(e);
12 }
13 actions.setIsLoading();
14 }),
15 getUserById: thunk(async (actions, id) => {
16 actions.setIsLoading();
17 try {
18 const { data } = await getUserById(id);
19 actions.setUser(data);
20 } catch (e) {
21 actions.setError(e);
22 }
23 actions.setIsLoading();
24 })
25});

In the code block above, we are getting a single user by an id from an API with a getUser thunk and using actions to set the user as our current state.

A thunk on Easy Peasy is used to dispatch an action that can modify or update an application’s state while providing us with the ability to handle side effects. Thunks can be defined in an easy peasy application by importing it from eay-peasy like below

1import { thunk } from 'easy-peasy';

Easy Peasy vs Redux/MobX/HookState

Similar to other state managers like Redux and MobX, Easy Peasy makes use of a single store to handle the application state, and it also appreciates the use of actions as a source of data for our application store. It’s important to note that Easy Peasy uses Redux internally to manage state.

Unlike Redux and MobX, Easy Peasy requires little to no boilerplate code to work with, Easy Peasy uses Immer under the hood, which gives developers the power to interact with data while keeping the benefits of the immutable data.

Easy Peasy allows developers to extend the application store by using Redux middlewares and other custom hooks to enhance performance.

Compared to React HookState, Easy Peasy offers more ease of managing and updating state with a single store and sharing information with component using custom hooks such as useStoreState and useStoreAction which comes out of the box with Easy Peasy.

With its ease and zero boilerplate code, Easy Peasy can be used to manage state from simple React to-do applications to larger applications. Easy Peasy also provides a support for TypeScript out of the box.

Building Notes application with Easy Peasy

Now that we know the core concepts of Easy Peasy, we’ll be building a notes application and managing the state with Easy Peasy. The application will allow users to add, delete and temporary cancel a note using a toggle.

Setting Up Your Environment

First, let’s create a new React application, write the code block below on your terminal

1npx create-react-app easy-peasy-notes-app

The above code will create a bare React application using the create-react-app package. Move into the project directory and add the dependencies we’d need for our application.

1cd easy-peasy-notes-app
1yarn add easy-peasy uuid

In the above code block, we installed

  • easy-peasy: our state manager for our application
  • uuid: This is for creating unique string of notes for our application

If you’ve done this, then start the project server using the command below

1yarn start

Next, let’s create a components folder in our src directory, we’d be creating three components and an app store for our application.

Creating the App Store

As mentioned above, Easy Peasy works with a store to hold the application state. With this we can access the application store and update the state. In the store, we’d need to set up a function to add, toggle and delete notes in our application.

To create our app store, first create a Store.js file in our project’s src directory, next let’s add logic to our store:

1import { action } from "easy-peasy";
2import uuid from "uuid";
3
4export default {
5 notes: [],
6 setNote: action((state, notes) => {
7 state.notes = notes;
8 }),
9 addNote: action((state, note) => {
10 note.id = uuid.v4();
11 state.notes.push(note);
12 }),
13 toggleNote: action((state, id) => {
14 state.notes.forEach((note) => {
15 return note.id === id ? (note.completed = !note.completed) : note;
16 });
17 }),
18 removeNote: action((state, id) => {
19 state.notes = state.notes.filter((note) => note.id !== id);
20 })
21};

In the code above, we imported actions from easy-peasy, the actions will be used to update our application store, we imported uuid to give unique ids to our notes when they are created. We initialized notes as an empty array and created a function setNote that takes in the state and note parameters and sets the current note as the value for state.notes.

The addNote function takes in two parameters, an initial state and a note, next we assigned the note id to one automatically provided by uuid.v4() and pushes the new note into the state.notes array.

The toggleNote takes in the state and id parameters and using the native JavaScript forEach object to cross off completed notes by toggling the value of note.completed, the removeNote object deletes a note using the filter object.

We will use the logic above to create our application’s component in the next section.

Building the Note component

Here, we will build our note component which will be the basic component for how each list will look on our application, to do this, let’s create a components folder in the src directory of our project and create a new file Note.jsx and inside it, write the code block below.

1import React from "react";
2import { useStoreActions } from "easy-peasy";
3
4const Note = ({ note }) => {
5 const { completed } = note;
6 const removeNote = useStoreActions(actions => actions.removeNote);
7 const toggleNote = useStoreActions(actions => actions.toggleNote);
8 return (
9 <li className="d-flex justify-content-between align-items-center mb-2">
10 <span
11 className="h2 mr-2"
12 style={{
13 textDecoration: completed ? "line-through" : "",
14 cursor: "pointer"
15 }}
16 onClick={() => toggleNote(note.id)}
17 >
18 {note.title}
19 </span>
20 <button
21 onClick={() => removeNote(note.id)}
22 className="btn btn-danger btn-lg"
23 >
24 &times;
25 </button>
26 </li>
27 );
28};
29
30export default Note;

Here, the useStoreActions hook from easy-peasy give our Note component access to the actions in the store, in this case the toggleNote for crossing off a note as completed and addNote for adding a new note. We returned the li tag which contains the new note.

Next, we added a delete button for our application, similar to the toggling a note, we added an onClick event that takes in the removeNote action, if we did this correctly our app should look like the image below.

Notes component

Building Notes component

This component will act as a render for our notes, here we will add a header component for our application name and render all our notes in this component, let’s do that below

1import React from "react";
2import { useStoreState } from "easy-peasy";
3import Note from "./Note";
4const Notes = () => {
5 const notes = useStoreState((state) => state.notes);
6 return (
7 <>
8 <h1 className="display-4">Notes</h1>
9 {notes.length === 0 ? (
10 <h2 className="display-3 text-capitalize">Please add note</h2>
11 ) : (
12 notes.map((note) => <Note key={note.id} note={note} />)
13 )}
14 </>
15 );
16};
17export default Notes;

Here, we imported the [useStoreState](https://easy-peasy.now.sh/docs/api/use-store-state.html) hook from easy-peasy, the useStoreState grants our component access to the store’s state, next we created a functional component notes and using the useStorestate we assigned notes to the state of the application found on the store.

As an edge case using a tenary operaor, we will drop a text for the user to add a note if they haven’t and to render a note if they did. You can learn more about tenary operators here.

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.

Building NotesForm Component

This component will be the bulk of our application, here will will handle submitting our notes and setting it as the updated value of our application state. Let’s build the component below

1import React, { useState } from "react";
2import { useStoreActions } from "easy-peasy";
3
4const NotesForm = () => {
5 const [title, setTitle] = useState("");
6 const [err, setErr] = useState(false);
7 const addNote = useStoreActions(actions => actions.addNote);
8 const handleSubmit = e => {
9 e.preventDefault();
10 if (title.trim() === "") {
11 setErr(true);
12 } else {
13 setErr(false);
14 addNote({
15 title,
16 completed: false
17 });
18 }
19 setTitle("");
20 };
21 return (
22 <>
23 <form onSubmit={handleSubmit} className="d-flex py-5 form-inline">
24 <input
25 type="text"
26 placeholder="Add Todo Title"
27 value={title}
28 className="form-control mr-sm-2 form-control-lg"
29 onChange={e => setTitle(e.target.value)}
30 />
31 <button type="submit" className="btn btn-success btn-lg rounded">
32 Add Note
33 </button>
34 </form>
35 {err && (
36 <div className="alert alert-dismissible alert-danger">
37 <button
38 type="button"
39 className="close"
40 data-dismiss="alert"
41 onClick={() => setErr(false)}
42 >
43 &times;
44 </button>
45 <strong>Oh oh!</strong>{" "}
46 <span className="alert-link">please add a valid text</span></div>
47 )}
48 </>
49 );
50};
51export default NotesForm;

In this component, first in order to access our project’s action objects in the store, we imported the useStoreActions and initialized the addNote action for adding a note in our component, next we created an input form that includes input for adding notes, submitting a note to be added and a button for alert for when a user tries to add an empty note using the input.

A final act will be to setup our App.js file and wrap our application using a Provider and restart our server to see our final application, let’s do tht in the code block below.

1import React from "react";
2import "./styles.css";
3import Notes from './components/Notes';
4import NotesForm from './components/NotesForm'
5
6import { StoreProvider, createStore } from "easy-peasy";
7import store from "./Store";
8
9const Store = createStore(store);
10function App() {
11 return (
12 <StoreProvider store={Store}>
13 <div className="container">
14 <NotesForm />
15 <Notes />
16 </div>
17 </StoreProvider>
18 );
19}

Here, we have imported the StoreProvider and createStore, the StoreProvider exposes the store to our application so that our components will be able to able to consume the store using hooks while the createStore similar to Redux creates a global store based on the models we’ve provided, next we wrapped our App component using the store as a parameter of the StoreProvider.

Once done correctly, our app should look like the image below

Easy peasy note application

API Request with Easy Peasy

In this section, we are going to look at handling API requests with Easy peasy, to better understand this, we will be building a currency converter using React, TypeScript and Easy peasy to manage the state of the application. In our application, users should be able to convert dollars to any currency, users can input the amount they’d like to convert and the currency they’re converting to.

First, we will create a react app using the command below

1npx create-react-app currency-converter

We will add typescript support and reactstrap for styling using the Yarn package manager

1yarn add @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/jest @types/node @types/react @types/react-dom axios bootstrap easy-peasy reactstrap typescript

For TypeScript support, create a tsconfig.json file in the root directory of our project and copy the code block below into it

1{
2 "compilerOptions": {
3 "target": "es5",
4 "lib": [
5 "dom",
6 "dom.iterable",
7 "esnext"
8 ],
9 "allowJs": true,
10 "skipLibCheck": true,
11 "esModuleInterop": true,
12 "allowSyntheticDefaultImports": true,
13 "strict": true,
14 "forceConsistentCasingInFileNames": true,
15 "noFallthroughCasesInSwitch": true,
16 "module": "esnext",
17 "moduleResolution": "node",
18 "resolveJsonModule": true,
19 "isolatedModules": true,
20 "noEmit": true,
21 "jsx": "react-jsx"
22 },
23 "include": [
24 "src"
25 ]
26}

After we’ve added the code above, to finish TypeScript configuration for our project, create a new file in the root directory of our project named react-app-env.d.ts, this file will reference the type of react-scripts we’d have in our project, you can learn more about it here.

1/// <reference types="react-scripts" />

Building Our App’s Store

To get started on our project proper, in the src directory of your project, create a store folder for our app’s store and inside it, create two files, index.ts and typehook.ts. Our index.ts file will contain our TypeScript interfaces for our API functions and our application store actions while our typehook.ts will contain Typed hooks from Easy peasy. In the code block below, we will create interfaces for our API requests

1import { createStore, Action, action, Thunk, thunk } from "easy-peasy";
2import axios from "../axios";
3
4export interface ICurrency {
5 currency_name: string;
6 currency_code: string;
7 decimal_units: string;
8 countries: string[];
9}
10interface IAllCurrencies {
11 data: ICurrency[];
12 updateResult: Action<IAllCurrencies, ICurrency[]>;
13 getAllCurrencies: Thunk<IAllCurrencies>;
14}
15interface ICurrencyRates {
16 rates: { [key: string]: string };
17 updateRates: Action<ICurrencyRates, any>;
18 getCurrencyRates: Thunk<ICurrencyRates>;
19}
20interface IConversion {
21 data: {
22 to: string;
23 amount: string;
24 };
25 updateTo: Action<IConversion, string>;
26 updateAmount: Action<IConversion, string>;
27}
28export interface IStore {
29 allCurrencies: IAllCurrencies;
30 currencyRates: ICurrencyRates;
31 conversion: IConversion;
32}
33
34const store = createStore<IStore>({
35 allCurrencies: {
36 data: [],
37 updateResult: action((state, payload) => {
38 state.data = Object.values(payload);
39 }),
40 getAllCurrencies: thunk(async (actions) => {
41 try {
42 const res = await axios.get(`/currencies`);
43 actions.updateResult(res?.data?.response?.fiats);
44 } catch (error) {
45 console.log(error);
46 }
47 }),
48 },
49 currencyRates: {
50 rates: {},
51 updateRates: action((state, payload) => {
52 state.rates = payload;
53 }),
54 getCurrencyRates: thunk(async (actions) => {
55 try {
56 const res = await axios.get(`/latest`);
57 actions.updateRates(res?.data?.response?.rates);
58 } catch (error) {
59 console.log(error);
60 }
61 }),
62 },
63 conversion: {
64 data: {
65 to: "",
66 amount: "",
67 },
68 updateTo: action((state, payload) => {
69 state.data.to = payload;
70 }),
71 updateAmount: action((state, payload) => {
72 state.data.amount = payload;
73 }),
74 },
75});
76export default store;

Here, we created interfaces, which defines the contract on the properties we have, for example in ICurrency we enforced the name, code, decimal units and countries to be of type string.

In IAllCurrencies we defined the data we’ll get from the API as an array containing the object we’ve defined in ICurrency, we also enforced our updateResult works based on the interface of IAllCurrencies and accepts a payload of ICurrency in an array while the getAllCurrencies method uses a Thunk to perform asynchronous functions.

We added an interface for ICurrencyRates, we defined rates to take in objects with keys which must be strings and also accept a string payload and updateRates will work with the data and any data type, getCurrencyRates uses Thunk to perform asynchronous functions with the data returned.

To create a store, we first called the easy-peasy store, in our case we structured the store to use the IStore interface, next we called the allCurrencies object from the IStore, inside it we will receive the data as an array.

Similar to Redux, to update a state in easy peasy, you’d use an action. We defined the action updateResult which acts as a reducer and takes in our current state and the user’s payload and sets the current state using the values we get from the user’s payload. You can learn more about updating the store and createStore.

To getAllCurrencies we performed an async operation using axios to get all currencies and use actions to set the data as the response, in the case of errors we wrapped the full application with a try…catch method. We performed similar functions in our currencyRate object, updating the state with an action and performing an async operation to get the latest rates from the API and setting the state using the data we receive.

The Conversion object converts the amount inputted by the user from dollars to any currency the user chooses, to display the amount we defined an action that updates and renders the amount converted to the user.

Building our Store Type Hooks

When using Easy Peasy with TypeScript, hooks are often recommended to have types, often this is done with interfaces defined in the project store. In this section, we will add types to the hooks we will be using in our application. To do this, inside of our store directory, create a new file called typehook.ts and inside it, write the code block below.

1import { createTypedHooks } from "easy-peasy";
2import { IStore } from "./index";
3
4const typedHooks = createTypedHooks<IStore>();
5
6export const useStoreActions = typedHooks.useStoreActions;
7export const useStoreDispatch = typedHooks.useStoreDispatch;
8export const useStoreState = typedHooks.useStoreState;

In the code block above, we are adding types to our useStoreActions, useStoreDispatch and our useStoreState hooks, with this we are configuring it to the interfaces we’ve defined in our IStore. By doing this, whatever actions we are dispatching here will come from actions from the store.

Building Header Component

In this section, we will add a Header to our application, the application header will contain our header, input fields for the user to add the amount and the currency they wish to convert. First, inside of our src directory, create a components folder and inside that folder, we’ll create a header folder, which will contain a header.tsx file. Let’s add the logic for this.

1import { useState } from "react";
2import { Button, Form, FormGroup, Input, Jumbotron } from "reactstrap";
3import { ICurrency } from "../../store";
4import { useStoreState, useStoreActions } from "../../store/typehook";
5
6const Header = () => {
7 const allCurrencies = useStoreState((state) => state.allCurrencies.data);
8 const setAmountToConvert = useStoreActions((actions) => actions.conversion.updateAmount);
9 const setCurrencyToConvertTo = useStoreActions((actions) => actions.conversion.updateTo);
10 const [to, setTo] = useState<string>("");
11 const [amount, setAmount] = useState<string>("");
12
13 const onSubmitHandler = (e: { preventDefault: () => void }) => {
14 e.preventDefault();
15 (to && amount) && setAmountToConvert(amount);
16 (to && amount) && setCurrencyToConvertTo(to);
17 };

In the code block above, we imported the ICurrency object from our store, we also imported useStoreState and useStoreActions from our custom typed hooks.

We initialized our Header as a functional component, next we create a constant allCurrencies to get the state of allCurrencies in our store. With setAmountToConvertTo, there we called an action, the action we called is the updateAmount action from the store.

Using React useState, we defined the state we want to update, we added a <string> to let our app know that state we are updating and defining is of string type.

To handle submit, we created a function onSubmitHandler which converts an amount and currency the user inputted on submit.

To finish our Header component, let’s render the input fields using react strap for our components and bootstrap for styling, to do that we’d append the code block below to the functions we’ve defined at the beginning of this section.

1return (
2 <div className="text-center">
3 <Jumbotron fluid>
4 <h1 className="display-4">Currency Converter</h1>
5 <div className="w-50 mx-auto">
6 <Form id='my-form' onSubmit={onSubmitHandler}>
7 <FormGroup className="d-flex flex-row mt-5 mb-5">
8 <Input
9 type="number"
10 value={amount}
11 onChange={(e) => setAmount(e.target.value)}
12 placeholder="Amount in Number"
13 />
14 <Input
15 type="text"
16 value="from USD ($)"
17 className='text-center w-50 mx-4'
18 disabled
19 />
20 <Input
21 type="select"
22 value={to}
23 onChange={(e) => setTo(e.target.value)}
24 >
25 <option>Converting to?</option>
26 {allCurrencies.map((currency: ICurrency) => (
27 <option
28 key={currency?.currency_code}
29 value={currency?.currency_code}
30 >
31 {currency?.currency_name}
32 </option>
33 ))}
34 </Input>
35 </FormGroup>
36 </Form>
37 <Button
38 color="primary"
39 size="lg"
40 block
41 className="px-4"
42 type="submit"
43 form='my-form'
44 >
45 Convert
46 </Button>
47 </div>
48 </Jumbotron>
49 </div>
50 );
51};
52export default Header;

Here, we built the input fields for our application, one for the amount to be converted and the currency, if done correctly our app should look similar to the image below.

Header component

Adding Currency API

To get the latest conversion rates and countries, we’d be using the rapid API currency API. To get started, first create a new folder axios in our src directory, inside this folder create a new file index.tsx.

Next is to visit Rapid API and sign up to get an apiKey, when we do this, paste your API base URL and API keys inside our index.tsx in the format below

1import axios from "axios";
2export default axios.create({
3 baseURL: "https://currencyscoop.p.rapidapi.com",
4 headers: {
5 "your api key goes here",
6 "x-rapidapi-host": "currencyscoop.p.rapidapi.com",
7 },
8});

To complete our application, let’s configure our App.tsx in the next section

Configuring App.tsx

First, we’d import all our actions and state from our typedhooks, initialize them in our App.tsx. Let’s do that below.

1import { useEffect } from "react";
2import { useStoreActions, useStoreState } from "./store/typehook";
3import Header from "./components/header/Header";
4
5const App = () => {
6 const getAllCurrencies = useStoreActions(
7 (actions) => actions.allCurrencies.getAllCurrencies
8 );
9 const getCurrencyRates = useStoreActions(
10 (actions) => actions.currencyRates.getCurrencyRates
11 );
12 const currencyRates = useStoreState((state) => state.currencyRates.rates);
13 const amountToConvert = useStoreState(
14 (state) => state.conversion.data.amount
15 );
16 const currencyConvertingTo = useStoreState(
17 (state) => state.conversion.data.to
18 );
19
20 useEffect(() => {
21 getAllCurrencies();
22 getCurrencyRates();
23 }, [getAllCurrencies, getCurrencyRates]);
24
25 const equivalence = () => {
26 const val = Number(currencyRates[currencyConvertingTo]);
27 return val * parseInt(amountToConvert);
28 };
29
30 return (
31 <div
32 style={{ background: "#E9ECEF", height: "100vh" }}
33 className="container-fluid"
34 >
35 <Header />
36 <div className="w-50 mx-auto">
37 {amountToConvert && currencyConvertingTo ? <h2>Result:</h2> : null}
38 {amountToConvert ? (
39 <h3>
40 ${amountToConvert} = {equivalence()}
41 </h3>
42 ) : null}
43 </div>
44 </div>
45 );
46};
47export default App;

Similar to what we did in our typedhooks file, in the code block above, we initialized all our store functions such as the getAllCurrencies and getCurrencyRates in this component. We used React useEffect hook to call the actions getAllCurrencies and getCurrencyRates from our store.

Next, we initialized a function equivalence that converts the currency rates from an object and returning the value we get from the API and multiplies it by the amount inputted by the user as an integer.

To conclude we used bootstrap and react strap to build components for our input. If done correctly, our app should look like this

easy peasy currency converter

Conclusion

In this article, we learnt about Easy-Peasy, a state manager for React applications that focuses on providing better experience for developers. We also went through the process of creating a notes application using Easy-Peasy, to manage the state and also detailed the pros of using easy-peasy to manage state for your next application. Have fun using easy-peasy for your next React application. A working version of the notes app can be found on Codesandbox, a working version of the currency converter can be found here.

RESOURCES

Pull Quotes

  1. Easy Peasy is an abstraction of Redux, providing a reimagined API that focuses on developer experience
  2. With Easy Peasy, developers can manage state with no boilerplate code while working with redux architectural guarantees.

More articles from OpenReplay Blog

Forever Functional - Pointfree Style Programming

Pointfree style programming is a way of calling functions without having to worry about parameters. Learn all about it here.

July 11th, 2021 · 4 min read

How to Use IndexDB to Manage State in JavaScript

Learn how to use IndexedDB for your state management needs using Vanilla JS

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