Search code examples
reactjsreduxredux-frameworkredux-thunk

Redux - why loading everything in state at root


I am trying to understand Redux and having some difficulty.

I understand the concept of combineReducer, ie ....

var reducer = combineReducers({
    user: userReducer,
    products: productsReducer
})

But what if I have thousands of products, only available on the products page. I do not understand why I need to load them at root; to me this will slow the initial start up of the app for something that will not be needed unless the user goes to the products page.

Is this just the way it is with redux?


Solution

  • In Redux apps, you always build your entire state at the start. With Redux you have one store and one state - everything should trickle down from that one state to props on your components. However, that does not mean you actually need to load all the data into the state at launch, only that the structure needs to be there. This is why you should set up an initial state object for each reducer.

    Let's say you have thousands of product records that you load from the database. In your products reducer you could do something like this:

    const initialState = {
        data: []
    };
    
    //use ES6 default parameters
    function productsReducer (state = initialState, action) {
        switch (action.type) {
        case 'GET_PRODUCTS':
            //return data from action
            return {
                data: action.result
            };
        default: 
            return state;
        }
    }
    

    This means that when you start your app, if you use the full reducer you declared in your post, your application state will look like this:

    {
        user: {},
        products: {
            data: []
        }
    }
    

    products.data will be an empty array until you fire an action that actually requires you to load the products data (i.e. you go to the Products page in your app or something). It's true that the products data will remain in your state if you then go elsewhere in your app, but this is a great thing - the next time you render the Products page you will already have the data at your disposal without having to do a database lookup.