Creating a Store

An introduction to creating a store.

We'll cover the following

In contrast to most other Flux implementations, in Redux, a single store holds all of the application states in one object. The store is also responsible for changing the state when something happens in our application. We could say that Redux is the store. When we talk about accessing the state, dispatching an action, or listening to state changes, it is the store that is responsible for all of it.

Sometimes the concern is raised that storing the whole state in one huge JavaScript object might be wasteful. But since objects are reference-type values and the state is just an object holding references to other objects, it doesn’t have any memory implications; it is the same as storing many objects in different variables.

Store creation

To create the store, we use the createStore() factory function exported by Redux. It accepts three arguments: a mandatory reducer function, an optional initial state, and an optional store enhancer. We will cover store enhancers later. We will start by creating a basic store with a dummy reducer that ignores actions and returns the state as it is:

import { createStore } from 'redux';

const initialState = {
  recipes: [],
  ingredients: []
};

const reducer = (state, action) => state;

const store = createStore(reducer, initialState);

The initialState parameter is optional, and usually, we delegate the task of building an initial state to reducers. However, it can be useful when you want to load the initial state from the server to speed up page load times.

The simple store that we have just created has five methods to access, change, and observe the state. They are:

  1. getState()
  2. dispatch()
  3. subscribe()
  4. replaceReducer()
  5. Symbol.observable

Together they make up the whole of the store’s API and most of the API Redux exports.

Get hands-on with 1200+ tech skills courses.