Let's break down react-redux completely
This article goes down for complete beginner on how to use redux and what are the important points to take in mind while creating your own state management in your react project.
What and why is Redux??
Redux is a state management library which is uesd to make a global management, it’s used to create a single source of truth and maintains a storage of data, preferences and other details which are
1) Used by the current user, stored on the local machine.
We want to maintain a set of data, that we can easily access. use and manipulalte according to the requirement, we will maintain the data for managing how other data will flow and create blocks or check points for the storage.
2) Less api calls, better user experience.
If there is an image required at multiple pages of an project, do we need to call that api every time we land a page?? Not necessary.
If i have a storage of data will not need to wait for the server to send me my data, which overall results in a better experience and more utilization of resources.
How to use redux in react.
To use redux in react we will need to do the following
Create a store.
Create reducers.
Combined reducers to manage states.
Action ceneter.
Reducers
These pure functions are called as reducers, they are the only way to change the state of the redux,
it will access the previous state and the action that is needed to be performed.
// reducers/eventLoading.js
export function eventLoadingReducer(state = false, action) {
switch (action.type) {
case "EVENT_LOADING":
return action.payload;
default:
return state;
}
}
Action Center
This returns the action object to dispatch. These action center will make the changes in the global state management, it access the new value and it passes as the payload
// actions/eventActions.js
export function setEventLoading(bool) {
return {
type: "EVENT_LOADING",
payload: bool,
};
}
Connecting to Redux Store
Heres is a complete picture now, we are connecting to the redux store from our page, like this page imports the action, maps it to props and also dispatches it to correct reducer.
// Inside your component file
import { setEventLoading } from "../actions/eventActions";
const mapStateToProps = (state) => ({
eventLoading: state.eventLoading, // Access state from reducer
});
const mapDispatchToProps = (dispatch) => ({
eventLoading: (bool) => dispatch(setEventLoading(bool)),
});