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:
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:
import { createStore, action } from 'easy-peasy';
export default createStore({});
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:
import { StoreProvider } from 'easy-peasy';
import store from '../store';
ReactDOM.render(
<React.StrictMode>
<StoreProvider store={store}>
<App />
</StoreProvider>
</React.StrictMode>,
document.getElementById('root')
);
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:
import { createStore, action } from 'easy-peasy';
export default createStore({
name: '',
setName: action((state, payload) => {
state.name = payload;
}),
});
Now, any component in your app can import useStoreState
and useStoreActions
from easy-peasy
to access the state and the defined actions, respectively.
import { useStoreState, useStoreActions } from 'easy-peasy';
// Accessing state properties
const name = useStoreState((state) => state.name);
// Accessing actions
const setName = useStoreActions((actions) => actions.setName);
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:
<button onClick={() => setName('newname')}>
Set name
</button>
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.