Skip to content
Related Articles

Related Articles

How to combine multiple reducers in ReactJS ?

Improve Article
Save Article
  • Last Updated : 22 Mar, 2022
Improve Article
Save Article

In ReactJs, when we are working with the redux state management tool. We use actions to perform actions and we have reducers to modify and create change in our state of redux. Most of the time we have multiple actions to perform and for that we have multiple reducers. Having multiple reducers become an issue later when we create the store for our redux.

To manage the multiple reducers we have function called combineReducers in the redux. This basically helps to combine multiple reducers into a single unit and use them.

Let’s create an application to demonstrate the above :

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app example

Step 2: After creating your project folder i.e. example, move to it using the following command:

cd example

Step 3: Install the following modules. From root directory of your project in terminal, run the following command:

npm install redux
npm install react-redux

Example: Let’s make a simple book list application with help of redux to understand to combine multiple reducers.

Project Structure: It will look like this.

project structure

In src folder, make three new folder components, actions, and reducer. In components add two js files named book-detail.js and book-list.js. In the actions folder, add a file index.js. In reducers, folder add three files index.js, reducer_book.js, and reducer_active_book.js.

Implementation: Write down the following code in respective files.

index.js




import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducers from "./reducers";
  
ReactDOM.render(
  <React.StrictMode>
     <Provider store={createStore(reducers)}>
    <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);


App.js




import React from "react";
import { Component } from "react";
  
import BookList from "./components/book-list";
import BookDetail from "./components/book-detail";
  
export default class App extends Component {
  render() {
    return (
      <div style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        width: "100%",
        height: "100vh"
      }}>
        <BookList />
        <BookDetail />
      </div>
    );
  }
}


In the components folder these files are as follows:

book-detail.js




import React, { Component } from "react";
import { connect } from "react-redux";
  
class BookDetail extends Component {
  render() {
    if (!this.props.book) {
      return <div>Select a book to get started.</div>;
    }
  
    return (
      <div>
        <h3>Details for:</h3>
        <div>Title: {this.props.book.title}</div>
        <div>Pages: {this.props.book.pages}</div>
      </div>
    );
  }
}
  
function mapStateToProps(state) {
  return {
    book: state.activeBook,
  };
}
  
export default connect(mapStateToProps)(BookDetail);


book-list.js




import React, { Component } from "react";
import { connect } from "react-redux";
import { selectBook } from "../actions/index";
import { bindActionCreators } from "redux";
  
class BookList extends Component {
  renderList() {
    return this.props.books.map(book => {
      return (
        <li
          key={book.title}
          onClick={() => this.props.selectBook(book)}
        >
          {book.title}
        </li>
      );
    });
  }
  
  render() {
    return (
      <ul>
        {this.renderList()}
      </ul>
    );
  }
}
  
function mapStateToProps(state) {
  return {
    books: state.books
  };
}
function mapDispatchToProps(dispatch) {
  return bindActionCreators({ 
    selectBook: selectBook }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(BookList);


In actions folder

index.js




export function selectBook(book) {
    return {
      type: "BOOK_SELECTED",
      payload: book
    };
  }


In reducers folder

index.js




import { combineReducers } from "redux";
import BooksReducer from "./reducer_books";
import ActiveBook from "./reducer_active_book";
  
const rootReducer = combineReducers({
  books: BooksReducer,
  activeBook: ActiveBook
});
  
export default rootReducer;


Here, in the above code, we are using combineReducers to combine 

  • BooksReducer
  • ActiveBook

Within in a single unit named as rootReducer.

reducer_book.js




export default function books() {
    return [
      { title: "Javascript The Good Parts", pages: 101 },
      { title: "Harry Potter", pages: 39 },
      { title: "The Dark Tower", pages: 85 },
      { title: "Eloquent Ruby", pages: 1 }
    ];
  }


reducer_active_book.js




export default function active(state = null, action) {
    switch (action.type) {
      case "BOOK_SELECTED":
        return action.payload;
    default:
        return state;
    }
  }


Step to run the application: Run the application using the following command:

npm start

Output:  

Output


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!