Benjamin Li
Benjamin Li

Reputation: 1697

React with Redux, how to design my state

My website has 3 pages, e.g. www.example.com.au/invoices, www.example.com.au/customers and www.example.com.au/suppliers.

In this case, how to organize the global Redux state, I mean the structure. should it look like below?

state = {
    invoices: {
        //invoices related data
    },
    customers: {
        //customers related data
    },
    suppliers: {
        //suppliers related data
    }
}

Upvotes: 0

Views: 102

Answers (3)

yadhu
yadhu

Reputation: 15632

state = {
    invoices: {
        //invoices related data
    },
    customers: {
        //customers related data
    },
    suppliers: {
        //suppliers related data
    }
}

this looks good.

If you're on invoices page and if you won't be accessing state.suppliers or state.customers, then you don't need to combineReducers all of them together.

You can lazy load reducers (dynamically and use store.replaceReducer to inject them into store). This saves you some bytes ;)

Some tips:

  • Separate business logic from views (components) and reducers.
  • Identify core reducers (those which are needed throughout the app) and others. Only create initial store with core reducers.
  • Split reducers and action creators into different files and lazy load reducers as required.

Upvotes: 1

bharadhwaj
bharadhwaj

Reputation: 2129

It is up to you on how to store. But a more convenient way to do is, having separate file for each of them and combine them as a single store.

i.e, your folder structure looks some what like this,

reducers/
    |---- index.js
    |---- customers.js
    |---- invoices.js
    |---- suppliers.js

Inside each of customers.js, invoices.js and suppliers.js, write their own reducers in each of them and combine them to a single large store in the index.js file using combineReducers() method from redux


Basically the flow is,

  • Write separate small-small reducers.
  • Import all the reducers in a single file(index.js).
  • Using combineReducers() combine them into a single large reducer and export it to store.

Hope it helps! :)

Upvotes: 1

Mark Williams
Mark Williams

Reputation: 2308

That looks a good start. I find it's a good idea to try and keep the state as normalized as possible - try thinking about it as a relational database.

This is a great article: https://medium.com/javascript-scene/10-tips-for-better-redux-architecture-69250425af44#.9c678jwib

as is http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

Upvotes: 2

Related Questions