Redux Fundamentals: creating and using stores

Hello! It's been a while! Like, a year to the day as I write this. Life happens, but I'm back to add to my continuing Redux fundamentals saga.

The last time I was here we were talking about how to combine reducers to create one reducer function that processes all of our app's state changes and returns a single object with all of our app's current state in it.

Today, let's discuss how to take that root reducer function and turn it into a persistent store that holds onto our app state, and notifies any other code that might cares when any state changes.

Redux gives us a simple function to turn a reducer into a persistent store: createStore. To create a store object from our reducer function, all you have to do is import { createStore } from 'redux'; and call it with your reducer function as the first argument:

const myStore = createStore(myRootReducer);

Now we have a myStore object that has three methods we can use:


myStore.dispatch({ /* some action */ }) will take the action object you pass and ensure all of the reducer functions inside your root reducer get to look at it and update their state accordingly. So, that LOGIN action from my last post could store someone's username when they log in successfully:

myStore.dispatch({ type: 'LOGIN', username: 'john', password: 'johndoe123' });

That's how you dispatch an action to a store.


The second method our store object has is getState which, as you might guess, returns the store's entire state object based on all the actions that have been dispatched to all of its reducers:

// logs: { username: 'john', isLoggedIn: true }


Lastly—and this is a function that leads nicely into an upcoming post about using Redux with React—a store object has a subscribe method. This how you tell the store that you want the opportunity to run some code when its state changes:

myStore.subscribe(() => {
    console.log('state change!', myStore.getState());

myStore.dispatch({ type: 'LOGIN', username: 'john', password: 'johndoe123' });
// logs: "state change! { username: 'john', isLoggedIn: true }"

As we can see, a store is just a simple wrapper object around a collection of reducer functions that holds onto our state for us as our app runs, and gives our app a chance to react to any state changes.

Again, next time we'll discuss how to use Redux and React together, so that we can actually start rendering our app and updating app state based on actions from our app's users. Catch you soon!