Create redux in 28 lines of code

shanoysinc

Shanoy Sinclair

Posted on September 15, 2020

Create redux in 28 lines of code

Its such an eye opener when you learn to create the tools you are using and get a glimpse of how some of its functionality works under the hood.

function createStore(reducer, initialState) {
    let state = initialState;

    function getState() {
        return state;
    }

    function dispatch(action) {
        state = reducer(state, action);
    }

    return { dispatch, getState };
}

function reducer(state = [], action) {
    switch (action.type) {
        case "add":
            return [...state, action.payload];
        default:
            return state;
    }
}

const store = createStore(reducer);
store.dispatch({ type: "add", payload: "learn to code" });
store.dispatch({ type: "add", payload: "react" });
store.getState();
//[ 'learn to code', 'react' ]
Enter fullscreen mode Exit fullscreen mode

inspired by: typeofnandev

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
shanoysinc
Shanoy Sinclair

Posted on September 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About