Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Handle Parent-Child Data Relationships in Redux

Working on React-Redux apps, you will have to pass and manage data between components. This guide covers handle parent-child data relationships.

Oct 26, 2020 • 4 Minute Read

Introduction

Redux is an excellent library for state management in client-side JavaScript-based apps. It is framework agnostic, meaning it can be used with any other UI or JavaScript framework. Redux maintains the state of the whole app in a single immutable state object, which cannot be accessed or modified directly.

When working on React-Redux apps, you will come across many use cases where you have to pass and manage data between components. In this guide, you will learn how to handle parent-child data relationships in Redux.

Passing Data Between Components

As mentioned earlier, you cannot change the state object or the global store directly. To change the state object, you need to use actions and reducers. An action is simply a JavaScript object that passes information to reducers, and reducers are pure functions that return an updated state based on the current action that was dispatched.

Consider an example where you have counters in the parent and child components. You need to update the counter in the parent component from the child component and vice-versa.

So the initial, or default, state will look as follows.

      const initialState = {
    parentCounter: 0,
    childCounter: 0,
};
    

To update the state you need to create a reducer, as shown below.

      function reducer(state = initialState, action) {
    switch (action.type) {
        case "INCREMENT_PARENT":
            return { ...state, parentCounter: state.parentCounter + 1 };
        case "INCREMENT_CHILD":
            return { ...state, childCounter: state.childCounter + 1 };
        default:
            return state;
    }
}
    

In the parent component, dispatch the INCREMENT_CHILD action so the reducer updates the counter in the child component. To make the dispatch method available as a prop, use the connect() method. Also, pass the mapStateToProps argument to the connect method so the parent's counter value is sent as the prop to the component.

      import React, { Component } from "react";
import { connect } from "react-redux";

import Child from "./Child";

class Parent extends Component {
  incrementChildCounter = () => {
    this.props.dispatch({ type: "INCREMENT_CHILD" });
  };
  render() {
    return (
      <div className="parent-component">
        <div>
          This is the parent component - [COUNTER: {this.props.counter}]
        </div>
        <button onClick={this.incrementChildCounter}>
          Increment Child Counter
        </button>
        <Child />
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  counter: state.parentCounter,
});

export default connect(mapStateToProps)(Parent);
    

Follow the same steps for the child component, except the child component needs to dispatch the INCREMENT_PARENT action.

      import React, { Component } from "react";
import { connect } from "react-redux";

class Child extends Component {
  incrementParentCounter = () => {
    this.props.dispatch({ type: "INCREMENT_PARENT" });
  };
  render() {
    return (
      <div className="child-component">
        <div>This is the child component - [COUNTER: {this.props.counter}]</div>
        <button onClick={this.incrementParentCounter}>
          Increment Parent Counter
        </button>
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  counter: state.childCounter,
});

export default connect(mapStateToProps)(Child);
    

In the main App component, wrap the Parent component with the Provider component from the react-redux package and pass the store as a prop.

      import { Provider } from "react-redux";
import { createStore } from "redux";

const store = createStore(reducer);

function App() {
  return (
    <div className="App">
      <Provider store={store}>
        <Parent />
      </Provider>
    </div>
  );
}
    

Conclusion

With Redux, you might complain that there is a lot of boilerplate and overhead for creating actions and reducers and architecting the app. Even Redux suggests that you should start with a basic React app and use Redux only when the app state grows and it becomes difficult to predict state. You can refer to this section of the Redux docs to read more on the topic.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author