Revisit REDUX

Revisit REDUX

What is Redux?

Redux is a library that helps you manage state in your Javascript apps. This serves as the Data Layer for your apps. Redux follows Unidirectional Flow and that's why we need to use middleware's like thunk.

Okay, then why not multi-directional? Because managing a single copy of data is better than managing multiple copies also it might get difficult to understand where the application state is getting updated from.

Then, what's the application state? The same old object with datasets inside.

So, what is it that we require immediately before implementing Redux,

A clear understanding of data that's gonna be powering our components i.e the View Layer.

Code Samples

Let's move into the explanation. At first, actions. Let's see what it looks like

const fetchData = {
  dispatch ({
         type: 'FETCH_USER',
         payload: {
              data: userData.data.results,
         },
    });
};

So, what do we see

  1. They're simple objects
  2. They have a type, String to be specific.
  3. They have a payload with the changes that will be applied if the type matches.

Now reducers,

const initialState = {
  user: [ ],
};

export const dataReducer = (state = initialState, action) => {
  switch (action.type) {
    case "FETCH_USER":
      return {
        ...state,
        userData: action.payload.userData,
      };
    default:
      return { ...state };
  }
};

Let's see:

  1. Reducers are pure functions.
  2. It receives two arguments.
  3. It must return a state.
  4. If there are multiple reducers, we must combine them.

Now the store

import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import { dataReducer } from "./reducers/root";

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export const store = createStore(
  rootReducer,
  composeEnhancer(applyMiddleware(thunk))
);

Points to focus on:

  1. Store must be created on top of the app.
  2. Store can hold a maximum of two properties (the reason why we create a root reducer and call it inside the store).
  3. This is where thunk facilitates its asynchronous properties.

It also provides methods like

  • store.getState()

  • store.dispatch(action)

  • store.subscribe()

In a nutshell.

  1. Actions describe what's gonna happen.
  2. The actions get dispatched.
  3. They reach the store.
  4. Reducers are called by the store to respond to actions.
  5. Reducers takes the previous state and action and returns an updated state.
  6. Subscribers are called and then the view gets updated.

reduxflow.jpg

Let me know your thoughts on it.