Skip to content

Instantly share code, notes, and snippets.

@tmkelly28
Created April 12, 2017 14:52
Show Gist options
  • Save tmkelly28/5ac689b8de9b0da0bda2e2a377322c46 to your computer and use it in GitHub Desktop.
Save tmkelly28/5ac689b8de9b0da0bda2e2a377322c46 to your computer and use it in GitHub Desktop.

In this tutorial, we'll understand what the Redux store does by building it ourselves, step by step.


Part 1 - The Store

The main thing that Redux gives us is a method called createStore. We use createStore to get an instance of a store. We might imagine createStore as working like this:

function createStore () {
  return new Store(); // we'll write this constructor function ourselves shortly!
}

// now we can create a "store" object by invoking createStore
const store = createStore();

The Redux store also has "private" access (via closure) to two variables - the "currentState" (an object) and a "reducer" (a function that we'll write). Let's update our createStore function to include them:

function createStore () {

  let currentState = {};
  let reducer = null; // for now

  return new Store();
}

The Redux store is just an object with three methods (actually there's 4, but we won't bother with the fourth for now because chances are you'll never need it).

store.getState store.dispatch store.subscribe

Let's write a constructor function within our createStore:

function createStore () {

  let currentState = {};
  let reducer = null;

  // our constructor function
  function Store () {}
  // our .prototype methods
  Store.prototype.getState = function () {};
  Store.prototype.dispatch = function () {};
  Store.prototype.subscribe = function () {};

  return new Store();
}

The store.getState method is pretty easy - it just gives us access to that private currentState object!

function createStore () {

  let currentState = {};
  let reducer = null;

  function Store () {}
  Store.prototype.getState = function () {
    return currentState; // piece of cake!
  };
  Store.prototype.dispatch = function () {};
  Store.prototype.subscribe = function () {};

  return new Store();
}

Now we can get the "currentState" object that the store is holding. But how do we change the state? We need two things:

  • A "reducer" function, which will change the currentState object
  • Our store.dispatch method, which will expose the ability to invoke the reducer to us (similar to the way getState exposes the currentState to us)

In the next section, we'll talk about the "reducer" function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment