All articles

Build your own "redux" from scratch

lang
EN
link
date
Sep 17, 2021
slug
own-redux
status
Published
tags
React
summary
Redux is probably a buzz word that slips into the lingo of React developers. If your reaction has been like mine, it’s always been one of those things where I didn’t know much about it other than this official definition. I never could answer: “Why should I use Redux?”
type
Post

What is redux

According to the official documentation, Redux is a predictable state container for JavaScript apps. It is agnostic to React, however, we are going to be looking into its use cases and benefits for use with React.
Redux is probably a buzz word that slips into the lingo of React developers. If your reaction has been like mine, it’s always been one of those things where I didn’t know much about it other than this official definition. I never could answer: “Why should I use Redux?”
This tutorial is to help you better understand how redux works
You can find full source code here:

Store

Store is like a data warehouse, it stores all the state
JavaScript
const initMilkState = {
  milk: 0,
};

Action

Action contains the action type and payload, which can be used to change the state in Store
JavaScript
{ type: "PUT_MILK" }

{ type: "TAKE_MILK" }

Reducer

Reducer is like a action dispatcher, it takes action as props and return the new state
JavaScript
function milkReducer(state = initMilkState, action: any) {
  switch (action.type) {
    case "PUT_MILK":
      return { ...state, milk: state.milk + 1 };
    case "TAKE_MILK":
      return { ...state, milk: state.milk - 1 };
    default:
      return state;
  }
}

A simple use of redux

JavaScript
import React, { useEffect, useState } from "react";
import { createStore } from "redux";

const initMilkState = {
  milk: 0,
};

function milkReducer(state = initMilkState, action: any) {
  switch (action.type) {
    case "PUT_MILK":
      return { ...state, milk: state.milk + 1 };
    case "TAKE_MILK":
      return { ...state, milk: state.milk - 1 };
    default:
      return state;
  }
}

function App() {
  const [milk, setMilk] = useState(0);

  useEffect(() => {
    store.subscribe(() => setMilk(store.getState().milk));
  }, []);

  return (
    <div className="app">
      <h1>{milk}</h1>
      <div>
        <button onClick={() => store.dispatch({ type: "PUT_MILK" })}>
          PUT_MILK
        </button>
        <button onClick={() => store.dispatch({ type: "TAKE_MILK" })}>
          TAKE_MILK
        </button>
      </div>
    </div>
  );
}

export default App;

Create a redux

createStore(reducer, enhancer)

reducer : use reducer to update the state
enhancer : enhancer can be used to apply middleware
return : store
Methods in createStore()
store.subscribe : subscribe to the state change, all the callbacks will be stored into a listeners array.
store.dispatch: dispatch action ,every dispatch will create new state and the subscribed callbacks will be triggered
store.getState : return current state。
JavaScript
export function createStore(reducer, enhancer) {
  // deal with enhancer first
  // enhancer use createStore to create a new createStore (with middleware)
  if (enhancer && typeof enhancer === "function") {
    const newCreateStore = enhancer(createStore);
    const newStore = newCreateStore(reducer);
    return newStore;
  }

  let state;
  let listeners = []; // store all the subscribe listeners

  // run all the listeners callback when dispatching
  function dispatch(action) {
    // use reducer to update the state
    state = reducer(state, action);

    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i];
      listener();
    }
  }

  // subscribe to the change of the state
  function subscribe(callback) {
    listeners.push(callback);
  }

  // return the state
  function getState() {
    return state;
  }

  const store = {
    subscribe,
    dispatch,
    getState,
  };

  return store;
}

applyMiddleware(...middlewares)

JavaScript
export function applyMiddleware(...middlewares) {
  // applyMiddleware should return a enhancer
  function enhancer(createStore) {
    // enhancer return a new createStore
    function newCreateStore(reducer) {
      const store = createStore(reducer);

      // map all the middlewares
      const chain = middlewares.map((middleware) => middleware(store));
      const { dispatch } = store;

      // use compose to create a combined dispatch function (middlewares will be be triggered in order)
      const newDispatchGen = compose(...chain);

      // run the combined dispatch function
      const newDispatch = newDispatchGen(dispatch);

      // replace the old dispatch method with the new one
      return { ...store, dispatch: newDispatch };
    }

    return newCreateStore;
  }

  return enhancer;
}

function compose(...funcs) {
  return funcs.reduce(
    (a, b) =>
      (...args) =>
        a(b(...args))
  );
}

combineReducers(reducerMap)

JavaScript
export function combineReducers(reducerMap) {
  const reducerKeys = Object.keys(reducerMap);
  const reducer = (state = {}, action) => {
    let newState = {};

    for (const key of reducerKeys) {
      const currentReducer = reducerMap[key];
      const prevState = state[key];
      // loop all the reducers and try to dispatch the action
      // Note that all the reducers will be triggered, so do not use the same action name across the reducers !!!
      newState[key] = currentReducer(prevState, action);
    }

    return newState;
  };

  return reducer;
}

Test

JavaScript
import React, { useEffect, useState } from "react";
import "./App.css";
import {
  createStore,
  combineReducers,
  applyMiddleware,
} from "./customRedux/myRedux";
import logger from "./customRedux/logger";
import thunk from "./customRedux/thunk";

const initMilkState = {
  milk: 0,
};

function milkReducer(state = initMilkState, action: any) {
  switch (action.type) {
    case "PUT_MILK":
      return { ...state, milk: state.milk + 1 };
    case "TAKE_MILK":
      return { ...state, milk: state.milk - 1 };
    default:
      return state;
  }
}

const initRiceState = {
  rice: 0,
};

function riceReducer(state = initRiceState, action: any) {
  switch (action.type) {
    case "PUT_RICE":
      return { ...state, rice: state.rice + 1 };
    case "TAKE_RICE":
      return { ...state, rice: state.rice - 1 };
    case "BIG_RICE":
      return { ...state, rice: state.rice + action.payload };
    default:
      return state;
  }
}

let reducer = combineReducers({
  milkState: milkReducer,
  riceState: riceReducer,
});

let store = createStore(reducer, applyMiddleware(thunk, logger));

function App() {
  const [milk, setMilk] = useState(0);
  const [rice, setRice] = useState(0);

  useEffect(() => {
    store.subscribe(() => setMilk(store.getState().milkState.milk));
  }, []);

  useEffect(() => {
    store.subscribe(() => setRice(store.getState().riceState.rice));
  }, []);

  const handleBigRice = (amount: number) => {
    return (dispatch: any) => {
      dispatch({
        type: "BIG_RICE",
        payload: amount,
      });
    };
  };

  return (
    <div className="app">
      <h1>{milk}</h1>
      <div>
        <button onClick={() => store.dispatch({ type: "PUT_MILK" })}>
          PUT_MILK
        </button>
        <button onClick={() => store.dispatch({ type: "TAKE_MILK" })}>
          TAKE_MILK
        </button>
      </div>
      <h1>{rice}</h1>
      <div>
        <button onClick={() => store.dispatch({ type: "PUT_RICE" })}>
          PUT_RICE
        </button>
        <button onClick={() => store.dispatch({ type: "TAKE_RICE" })}>
          TAKE_RICE
        </button>
        <button onClick={() => store.dispatch(handleBigRice(5000))}>
          A BIG BOWL OF RICE
        </button>
      </div>
    </div>
  );
}

export default App;