Abhishek
Abhishek

Reputation: 357

Shall we use multiple combine reducers?

I have three reducers

I have one combine reducer for above three. But I want to divide project structure into multiple reducers. Is it a good practice to have multiple combine reducer in the project?

Upvotes: 8

Views: 5560

Answers (2)

Ardalan Farkhondeh
Ardalan Farkhondeh

Reputation: 76

Yes, you can combine multi reducer and use it as one store,

  1. Firstly, you should import all reducers in a new file. then, combine all reducers with combine-reducer technics,like this:

    import { combineReducers } from 'redux'; import {Home,Listing,Detail} from '*/**';

    const rootReducer = combineReducers({ Home, Listing, Detail })

    export default rootReducer

  2. Secondly, import the new file in Store file and create your store with combined-reducer

    import { createStore } from 'redux' import rootReducer from '*/combinestores'

    const store = createStore(rootReducer) console.log(store.getState())optinal

    export default store

  3. In the end, in your container you can use your store like this : (but before it, you should be sure send store as props to Containers)

    const mapStateToProps = state => {

     return{
        *name of your var* :  state.Home.*,
        *name of your var* :  state.Detail.*  /*then you can use this var as props anywhere you need*/
     }
    

    }

    const mapDispatchToProps = dispatch => { return{

         *name of your var* : () => dispatch ( *name of your func*()),
         *name of your var* : () => dispatch ( *name of your func*())
    
    
     }
    

    }

    export default connect(mapStateToProps,mapDispatchToProps)(name of func);

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 282160

Yes, you can have multiple combineReducers in your App, You can at the top level combine reducers Home , Listing and Detail and even split each individual reducers into multiple and combine them into one.

According to the Redux docs:

You may call combineReducers at any level of the reducer hierarchy. It doesn't have to happen at the top. In fact you may use it again to split the child reducers that get too complicated into independent grandchildren, and so on.

Some more description about combineReducer:

As your app grows more complex, you'll want to split your reducing function into separate functions, each managing independent parts of the state.

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.

The resulting reducer calls every child reducer, and gathers their results into a single state object. The shape of the state object matches the keys of the passed reducers.

Upvotes: 11

Related Questions