Redux

Suprabha - Jun 4 '20 - - Dev Community

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:

  1. You have reasonable amounts of data changing over time
  2. You need a single source of truth for state
  3. You find that keeping all the state in a top-level component is no longer sufficient

Installation:

$ npm install –save redux
Enter fullscreen mode Exit fullscreen mode

There will be some more packages which we need to install for the React bindings and the developer tools.

$ npm install –save react-redux
Enter fullscreen mode Exit fullscreen mode
$ npm install –save-dev redux-devtools
Enter fullscreen mode Exit fullscreen mode

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
})
Enter fullscreen mode Exit fullscreen mode

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: []
}
Enter fullscreen mode Exit fullscreen mode

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
         }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this article ♥

I hope you found this blog helpful, If you have any question please reach out to me on @suprabhasupi 😋

🌟 Twitter 👩🏻‍💻 Suprabha.me 🌟 Instagram
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .