Creating a Store
Learn how to create a Redux store, get the current state from the store, and pass actions to update the stored state.
The createStore
function
To create a store that will manage the global state, we have to import the createStore
function from the redux
package. We can call it by passing it a reducer function. This function returns a store object to us, which contains all the methods necessary to interact with the store-namely, dispatch
, getState
, and subscribe
. The latter two are not of the same importance when working with React, but we have mentioned them for the sake of completion. In React and Redux applications, the react-redux
binding components take care of the rerendering
of components if they are affected by a change of the state. Let’s look at an example:
import { createStore } from 'redux';
const initialState = 0;
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'PLUS': {
return state + (action.payload || 0);
}
case 'MINUS': {
return state - (action.payload || 0);
}
default: {
return state;
}
}
};
const store = createStore(counterReducer);
We’ve just created our first simple store with a counter reducer. The createStore
function only takes a single parameter in this example (the counterReducer
), indicating that the initial state
is set to undefined
. So, we’ve set the initialState
as the standard parameter, which equates to 0
in this example.
If we pass another parameter to the createStore
function, this parameter is passed as the first state to our reducer function:
const store = createStore(counterReducer, 3);
Instead of undefined
, the initial value for our state
parameter passed to the counterReducer
would equate to 3
. The initialState
would not be set, and our counter would start counting at 3
instead of 0
.
The first initial action being dispatched takes the form of:
{type: '@@redux/INIT5.3.p.j.l.8'}
Looking at our example, this means that the default
case will activate and that only the state
passed will be returned (which also equates to the initialState
).
This default
case is important. If no other case
of the switch
statement can be fulfilled, the current state
needs to be returned from the function to avoid unwanted side effects. The reducer
function is executed after each dispatch
call and dictates the value of the next state by returning it from the function.
Getting state using store.getState()
Calling store.getState()
after initialization, we obtain an initialState
of 0
:
Get hands-on with 1200+ tech skills courses.