Introduction of Redux

What is Redux?

Redux is quite an excellent State Management Framework. It's used with React.js library. To understand what is redux we have to learn what is the state.

State

state is the place where the data comes from. Our state as simple as possible and minimize the number of stateful components. This is the Javascript object that stores a component's behavior. state is dynamic, it enable a component to keep track of changing information in between renders and for it to be dynamic and interactive.

It can only be used within a class component. State is similar to props but unlike props. It is private to a component and is controlled solely by he said component. state is accessed using this.state as well as State is initiated using this.state. But, all subsequent changes to state are made using this.setState. this.setState ensures that the components affected by he change in state are re-rendered in the browser.

The main difference between state and props is that props  are immutable.

 Why we should choose Redux?

Redux and Flux are state management libraries. They add another layer of abstraction to your application. Redux also offers a lot of convenience for a Javascript developer. Debugging, action replaying 
  • Multiple React components needs o access the same sate but don't have any parent/ child relationship
  • You start to fell awkward passing down the state to multiple components with props.
This is not useful for smaller apps.
The store in Redux  is like the human brain. It's kind of magic. The Redux store is fundamental. The state of the whole application lives inside the store.So, we should create a store for wrapping up the state.  Redux cannot have multiple stores. The stores divided into various state objects. Therefore, we could maintain it through single store.

Three principles of Redux

  1. Single source of truth.
  2. The state is read-only
  3. Change are made with pure functions.
It is the state of our whole application is stored in an object within a single store. There is an only way to change the state is to emit an action, an object describing what happened.


01) Install the Redux on React dev environment


  1. npm install --save react-redux

02) Create a directory for the store


  1. mkdir -p src/js/store

Create the file named index.js in src/js/store and initialize the store.

  1. // src/js/store/index.js
  2. import { createStore } from "redux";
  3. import rootReducer from "../reducers/index";
  4. const store = createStore(rootReducer);
  5. export default store;
Store is the results of createStore which in turn is a function from the redux library. createStore takes a reducer as the first argument, you may also pass an initial state into createStore which is useful for server side rendering.


Reducers

Reducer is a Javascript function. A reducer takes two parmeters 
  1. The current state
  2. action
Reducers are most important concept in redux. Reducers are produce the state of the application. Usually react component the local state changes in place with setState. But, in Redux we can't do like that. The third principle of redux that the state is immutable(cannot change) in place.

Create reducers

To creating reducers we should use two parameters with plain Javascript function. 

  1. First parameter : simple reducer taking the initial state.
  2. Second parameter : action
  1. // src/js/reducers/index.js
  2. const initialState = {
  3. articles: []
  4. };
  5. function rootReducer(state = initialState, action) {
  6. return state;
  7. };
  8. export default rootReducer;


Actions

The second principle of Redux says that how to change the state is by sending signal to the store. The signal is action. Actions are payloads of information which send the data from your application to your store. We can send them by using store.dispatch().This is the process of sending signal. Actions are plain Javascript objects.Actions must have a type property that indicate the type of action being performed. Types should typically be defined as string constants.
import { ADD_TODO, REMOVE_TODO } from '../actionTypes'

Action Creators

Action creators are exactly the function that create actions.
export function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}
The type property is string . The reducer will use that string to determine how to calculate the next state.To avoiding errors we better to declare a action type as a constant.

Create a file name as acionType.js
  1. // src/js/constants/action-types.js
  2. export const ADD_ARTICLE = "ADD_ARTICLE";
You can update the action to use action type as below

  1. // src/js/actions/index.js
  2. import { ADD_ARTICLE } from "../constants/action-types";
  3. export function addArticle(payload) {
  4. return { type: ADD_ARTICLE, payload };
  5. }

Handling action

For handling every action type , a reducer function may use switch statement (if also possible). The reducer calculates the next state depending on the action type.It should return the initial state when no action type matches.The reducer is a pure function that takes the previous state and an action,and returns  the next state.

  1. (previousState , action) => newState

 It's call a reducer because it's he type function you would pass to Array.prototype.reduce(reduce, ?initialValue) 
we should never do inside a reducer :
  • Mutate its arguments.
  • Perform side effects like API calls and routing transitions.
  • Call non-pure functions
  1.  import { VisibilityFilters } from './actions'
    
    const initialState = {
      visibilityFilter: VisibilityFilters.SHOW_ALL,
      todos: []
    }
    
    function todoApp(state, action) {
      if (typeof state === 'undefined') {
        return initialState
      }
    
      // For now, don't handle any actions
      // and just return the state given to us.
      return state
    }
    

 Store

A store is an object that brings them together. A store has following responsibilities.

  • Holds application state.
  • Allows access to state via getState();
  • Allows state to be updated via dispatch(action).
  • Registers listeners via subscribe(listener).
  • It handles unregistering of listeners via the funcion retuned by subscribe(listener)
 It is important to note that you will have single sore in a redux application. If you want to split your datahandling logic, you will use reducer composition instead of many stores.


  1. import { createStore } from 'redux'
    import todoApp from './reducers'
    let store = createStore(todoApp)
    
For more guidence you can follow https://redux.js.org/








Comments

Popular posts from this blog

Easy understanding of MVC design architecture

A / B Testing

Firewall