The Core

The idea behind Redux is quite simple:

All the state of your application lives in a single store .

. To change the state of your application, you must dispatch an action .

an . Actions transform the state through the use of a reducer .

. When an action is dispatched, the store lets subscribers know the state has changed.

I’ll be implementing these using ES2015, transpiling with Babel and testing with Mocha and Chai. All code below is available on Github.

All the state of your application lives in a single store.

Redux exports the function createStore, which, as the name implies, creates and returns our store, the center of a redux application.

We’ll start here.

createStore takes two arguments, reducer and initialState. Let’s store the initialState as our current state for now.

We’ll need a way to access our state, the store supplies us with a getState method to do just that. This is also a good opportunity for us to write our first test.

Our state tree in this and future tests will resemble a simple note taking application. Our reducer here returns any argument passed into it, as we won’t be focusing on that just yet.

Let’s implement our method.

Great, now we can access our store’s state, but to change it we’ll need to dispatch an action.

To change the state of your application, you must dispatch an action, which transforms the state through the use of a reducer.

Let’s start out with another test

First we’re creating our notes reducer and an action creator, addNote, if you would like to learn more about reducers and action creators, the Redux Documentation is an excellent resource.

In our test, we’ll create our store, dispatch our action with a new payload and check to see if the store was successfully updated.

Let’s implement it!

Notice we’re instantly dispatching an INIT action. This will flow throw all our reducers and return the default state, setting up our store.

Great, almost there, the last step is to notify the store’s subscribers that a change has been made.

When an action is dispatched, the store lets subscribers know the state has changed.

We’ll need a way to subscribe to our store, let's write a test.

Since our listeners will be private, we’ll need update our dispatch method to notify listeners to pass this test.

We’ll go ahead and implement subscribe, which will add the passed function to an array of listeners, also, we’ll update our dispatch to let our listeners know something has changed.

Believe it or not, we’ve just implemented a simplified version of Redux!

Let’s look at one more function the redux package gives us, combineReducers.