An Overview of Redux

Redux is a non-persistence session-level state management technique. The data is available across the application until you refresh or close the browser.

There are three concepts available in redux:

  1. Action
  2. Reducer
  3. Store

Action:

Action is a plain JavaScript object, which sends data from the application / API to the redux store. It should have a “type” property, to identify the type of action being performed.

Example:

Reducer:

Reducer is a pure function (It will return the same output even if you are going to provide the same input multiple times). It will take two inputs (previous state, action) and return a new state (if condition true else previous state).

Reducer Composition:

Reducer composition is used to split the reducer into different parts to handle the functionality independently. You can use different keys to store the data in the store.

You can also use nested combineReducers.

Store:

The store is nothing but a javascript object which has the following responsibilities.

  1. Hold the application data in a single object.
  2. Access the store data via getState() method.
  3. Update the store using dispatch(action)
  4. Subscribe the listeners using subscribe(listeners) method.

We can create the store object using createStore() function.

We have to make sure we have only one store in the redux application. When we need to split the data processing logic, we have to use the reducer composition method instead of creating multiple stores.

You can also replace the reducer dynamically even after the creation of the store using the replaceReducer() function.

Data flow:

Redux basically follows the synchronous data flow.

  1. dispatch(action) — we can call the dispatch function from anywhere in our application (example: button click, lifecycle methods of react, onBlur,..)
  2. Calling Reducer method — the action is used to send the data with action type to the combineReducer function. The combine reducer executes the reducer and checks the action type matching reducer function. Once it’s found, the exact reducer will update the store data using the reducer key.
  3. Update store and return the updated store data to our react application.

React will wait until the flow is completed because by default redux follows the synchronous flow, to make it asynchronous, we have to use the middleware functionality.

Combine Redux with React:

We need to use the connect() method to combine the redux functionality with the react application. We can use the entire store data as a prop to our react component using the mapStateToProp function. We can use mapDispatchToProps function to dispatch our action from react component.

And, that’s an overview of Redux.

Leave a Reply

Your email address will not be published. Required fields are marked *

nineteen − six =