The Convenient React state management Library
Introduction
State management is a crucial aspect of every application, especially in React. While hooks like useState()
and prop passing can take us quite far, complex scenarios often call for a dedicated state management library. One such library I’ve come to appreciate is the easy-peasy
library, built on top of Redux. With its simplified approach to handling state, it allows for cleaner and more manageable code.
Installation
To start using easy-peasy
, simply install it using the following npm command:
1 | npm install easy-peasy |
Creating the Store
The first step is to create a store, where we’ll store the application state and the functions required to modify it. Create a store.js
file in the root of your project and add the following code:
1 | import { createStore, action } from 'easy-peasy'; |
Don’t worry; we’ll add more content to this file later.
Integrating the Store
Next, wrap your React app in the StoreProvider
component provided by easy-peasy
. The approach may vary depending on your setup. For instance, in a create-react-app project, add the following code to your index.js
file:
1 | import { StoreProvider } from 'easy-peasy'; |
This step ensures that the store is accessible in every component of your app.
Adding State and Actions
With the store set up, you can now add state and the corresponding actions to modify that state. Let’s begin with a simple example. Suppose we want to introduce a name
state and create a setName
action to update it. Modify the store.js
file as follows:
1 | import { createStore, action } from 'easy-peasy'; |
Now, any component in your app can import useStoreState
and useStoreActions
from easy-peasy
to access the state and the defined actions, respectively.
1 | import { useStoreState, useStoreActions } from 'easy-peasy'; |
With the state and actions available, you can call the setName
action in response to events in your app. For instance, you can trigger it on a button click like this:
1 | <button onClick={() => setName('newname')}> |
Any component consuming the state via useStoreState()
will automatically reflect the updated value.
Conclusion
This is just a simple example to get you started. With easy-peasy
, you can add as many state variables and actions as you need. By centralizing them in a store.js
file, you can easily scale and manage your application’s state.
tags: [“React”, “state management”, “easy-peasy”, “Redux”, “JavaScript”]