Lurker News

Comments (286) 115 threads

Show all comments

Showing thread 58 of 115

robbick1 reply#
Can't say I've seen enough to be confident on the best library but redux (https://github.com/reduxjs/redux) is just so simple, and has great, readable/understandable code.
icc97#
In Dan Abramov's excellent egghead redux course [0] he implements the `createStore` from scratch which is the core of redux, it's simple enough to post here:

  const createStore = (reducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = (action) => {
        state = reducer(state, action);
        listeners.map(listener => listener());
    };

    const subscribe = (listener) => {
        listeners.push(listener);
        // unsubscribe
        return () => {
            listeners = listeners.filter(l => l !== listener)
        };
    };

    // populate initial state
    dispatch({});

    return { getState, dispatch, subscribe };
  };

[0]: https://egghead.io/lessons/react-redux-implementing-store-fr...