Redux State Management

·

2 min read

Redux is an application data-flow architecture which is used for predicting state changes in JavaScript applications. Redux is not a framework. Redux can be used with any other View library but mostly used with React.

Dan Abramov created Redux in 2015. Redux was inspired greatly by functional programming language and FLUX architecture.

The main concepts of Redux architecture are:

Store : The place where the entire state of the application is stored

Actions : JS objects which encapsulate the events triggered within the application.

Reducers : Pure functions that modify the state of the application according to the actions triggered.

In Redux state is an immutable object. The state object cannot be changed directly in Redux. Triggering actions are the only way to modify the state. Every time the state is modified a new object should be returned which represents the modifications that are made to the state object.

Concept of Immutability :

Immutability means, values cannot be changed. To change immutable objects we need to create a copy of it and modify the copy.

In Redux state is an immutable object. The state object cannot be changed directly in Redux. Triggering actions are the only way to modify the state. Every time the state is modified a new object should be returned which represents the modifications that are made to the state object.

Handling immutability

There are many ways to handle immutability. Object.assign and spread operator for arrays are the most popular approach when working in ES6.

  1. Object.assign() .
  2. Spread Operator .

Middleware

  • Middleware need not be a pure function like reducers. It can cause side effects. So whatever functionality we could not put into reducer because reducers are pure can be put in middleware.

Uses of middleware

  1. It provides functionality between action and reducer. After an action is triggered and before its reduced middleware can take action.
  2. Organize all changes to the database (ajax calls) into one place
  3. Middleware allows pre-processing of actions. We can check for correct syntax, make sure they conform to your standards or edit them in some way like wrapping them in a function
  4. Perfect for debugging an application
  5. Allows us to keep actions clean so we need less boilerplate and fewer tests in our actions to make sure they are working correctly
  6. API calls are happening through middleware so if there is a mistake we can check middleware first.
  1. Redux Thunk
  2. Redux Saga

The most common requirement to use middleware is to support asynchronous actions. Middleware lets us dispatch async actions in addition to our regular actions.