Redux Basic Indroduction

1. What is Redux?

Redux is a predictable state container for JavaScript application. The state of your application is kept in a store, and each component can access any state that it needs from this store.

2. Why is Redux?

Most libraries like React, Angular, etc. are built with a way for components to internally manage their state without any need for an external library or tool. It does well for applications with few components, but as the application grows bigger, managing states shared across components becomes very hard.

In an app where data is shared among components, it might be confusing to actually know where a state should live. Ideally, the data in a component should live in just one component, so sharing data among sibling components becomes difficult. So that is why redux is come up with solving these issues by managing states in theapplication.

3. How Redux works?

  • Create the store.

1 is the default state.

  • By adding the reducer to store,we tell the store who responsible for changing the state. Here reducer is responsible for changing the state.

One reducer typically handle multiple actions. reducer always has to return state.

  • Then dispatch an action. This is how to dispatch an action.
  • dispatch action handle by the reducer. Reducer has switch statement and check the action type and return the new state.
  • After that new state is stored in the store.
  • subscribe method inform that state is changed.

Here this is the simple code to how the states are changed by redux.

In this example, same state is changed. Not created different states for every dispatchers.

In this example we are going to create new state object for every dispatchers.(immutable states)

4. Multiple reducers

Here we are going to use multiple reducers. Redux is support for multiple reducers. Here we are using combineReducers from redux library.

Important: Must use unique action types when we are using also multiple reducers. We are using one store. If we use same action type for different action, store couldn’t identify which action should be execute.

5. Redux Middleware

Middleware is executed before handling the action(before state is changed).

Here we are using applyMiddleware from redux library.

6. Redux Logger

In redux, there is nice user friendly logger called “redux-logger”. It is also library.

import logger from “redux-logger”;

References

https://blog.logrocket.com/why-use-redux-reasons-with-clear-examples-d21bffd5835/

https://www.smashingmagazine.com/2016/06/an-introduction-to-redux/

https://redux.js.org/faq/general/