Redux is a predictable state container for JavaScript apps. Need to understand the basic three principle. Here, you don’t need to use Babel or a module bundler to get started with Redux. (It integrates with reducer and action.)
When do you need to integrate redux with app:
- You have reasonable amounts of data changing over time
- You need a single source of truth for state
- You find that keeping all the state in a top-level component is no longer sufficient
Installation:
$ npm install –save redux
There will be some more packages which we need to install for the React bindings and the developer tools.
$ npm install –save react-redux
$ npm install –save-dev redux-devtools
Actions:
Actions are payloads of information that send data from our application to our store. They are the only source of information for the store. We send them to the store using store.dispatch()
(It’s an object that tells the reducer how to change data. It has only one requirement, it must be have type: property)
Here, is an example:
export const FETCH_PRODUCTS_LIST_SUCCESS = 'FETCH_PRODUCTS_LIST_SUCCESS';
export const fetchProductSuccess = products => ({
type: FETCH_PRODUCTS_LIST_SUCCESS,
payload: products
})
Reducer:
It specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.(It’s a function which returns some data. )
Here, is an example:
You will be importing FETCH_PRODUCTS_LIST_SUCCESS from actions
.
import {
FETCH_PRODUCTS_LIST_SUCCESS
} from '../actions/productAction'
const initialState = {
loading: false,
isCartEmpty: true,
products: []
}
You will be handling actions here:
export default function productReducer (state = initialState, action) {
switch(action.type) {
case FETCH_PRODUCTS_LIST_SUCCESS:
return {
...state,
loading: false,
isCartEmpty: true,
products: productList
}
default:
return state
}
}
Thanks for reading this article ♥
I hope you found this blog helpful, If you have any question please reach out to me on @suprabhasupi 😋
👩🏻💻 Suprabha.me |