Be the first user to complete this post

  • 0
Add to List

Redux: Implementing store from scratch

In redux, store is a very central piece which brings actions, reducers and states together. It has the following main functions and API :

  • Holds application state;
  • Allows access to state via getState();
  • Allows state to be updated via dispatch(action);
  • Registers listeners via subscribe(listener);
  • Handles unregistering of listeners via the function returned by subscribe(listener);.

Redux Store

[wpgist id="dcb86657def2bd9390a170b8a4f17092" file="store.js"]
Note: The subscribe function returns another function, which filters out the listener from the list of listeners. Hence, if you want to unsubscribe a listener then you will have to save the reference for the return value while subscribing and call the reference function. For example,

let foo = () => {...};

let unsubscribeFoo = store.subscribe(foo); // At this point foo will be called whenever the store updates

// sometime in future
unsubscribeFoo(); // After this function is executed, the foo will not be called whenever the store updates

Also Read:

  1. Use es6 and es6+ in eslint with babel
  2. Error handling in promises interview question
  3. Es6 Spread operator
  4. Generating container components with connect utility in react redux app
  5. Create Reducer for Redux Applications
  6. Dynamic module loading with require
  7. webpack with babel6 and react
  8. exports is not defined