Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the initialState used for in Redux createStore function

Tags:

redux

All:

When I read the source of Redux, in its createStore:

function createStore(reducer, initialState, enhancer) {
    ......
    var currentState = initialState;
    ......
    dispatch({ type: ActionTypes.INIT });
    ......
}

When create a new store, it sets currentState to initialState, and call reducer in init dispatch to update the default state value. I wonder: generally the currentStatew will be given a value from reducer, then what is the purpose of that initialState?

Thanks

like image 870
Kuan Avatar asked Dec 24 '22 08:12

Kuan


1 Answers

Normally, just specify the initial state as reducer default argument, and let each reducer manage it for themselves.

However in some cases you want to “hydrate” the state with existing data. For example, you might have saved the whole state tree in a localStorage and want to load it from there on startup, or maybe you are rendering on the server, and want to load the initial state you saved on the server from the HTML.

In this case, the initialState to createStore() is useful because it lets you optionally hydrate some parts of the tree where you have pre-populated data. In this case, it would “win” to the reducer default state which is usually the behavior you would want. The parts of the state tree that exist in initialState would be used as is, and the missing parts would be retrieved from the reducers. This makes it possible to “restore” some parts of the state, but always re-initialize the others.

Hopefully this answer should provide a more in-depth explanation of this technique.

like image 185
Dan Abramov Avatar answered Jan 14 '23 12:01

Dan Abramov