Author avatar

Manujith Pallewatte

Deciding When to Connect Your Component to the Redux Store

Manujith Pallewatte

  • Jun 21, 2019
  • 16 Min read
  • Jun 21, 2019
  • 16 Min read
Web Development


Redux is my go-to state management tool, when building a web app for scaling. Regardless of the hassle one has to go through initially, with a large enough codebase, everyone comes to a point where they’re thanking Redux for saving the day. A major headache of having Redux is the task of connecting your components to the Redux store and actions. Although it is often preferred to keep all Redux bindings at one place (usually the top most component), the practice soon gets messy with complex component hierarchies.


For this exercise, we will be building an extended version of the notorious ToDo app. While the boring ToDo apps simply have one type of item, ie: text items, our ToDo++ items can be a/an

  • text item
  • checklist item
  • item with actions
  • mix of the above

With this requirement in mind, let's initiate our design process with component decomposition. Firstly, we know that we only have one page, AppComponent, where we will show our items. But, as good front-end engineers, we always anticipate for later changes, so we would encapsulate our ToDo list functions in a new component and segregate the component from the page. ViewPageComponent will be the one and only page in our app. Just putting it there will prevent the confusion of having everything inside the App.js. So, our initial structure looks like:

2    |- ViewPageComponent
3        |- ToDoListComponent

What does a TodoList consists of? ToDoItems, of course. Although there's only four ToDo item types, at the moment, we would like to keep space for future additions. So, we decouple the items from the list. Then, we further decompose the item into atomic components, taking the idea from the requirements above.

2    |- ViewPageComponent
3        |- ToDoListComponent
4            |- ToDoItemComponent
5                |- TextComponent
6                |- CheckComponent
7                |- ButtonComponent

Note The relationship between the ToDoItemComponent and the atomic components is not inheritance but aggregation. The reason for this is that each ToDoItem will contain one or more of the atomic components, rather than just being one of the components.

Now that the component breakdown is completed, let's dive into implementation.

The Boilerplate

If you are too bored to setup the React-Redux project from scratch, you can go ahead and clone the code from the GitHub repo.

For the rest, let's start off by creating a new React app using the React CLI. In your terminal, generate the app with following command:

1$ create-react-app todoplus
2$ cd todoplus

Next, we add Redux to our project:

1$ npm install --save redux react-redux

Once done, we create the page component and initialize the store, actions, and reducer for Redux. The directory structure for source is as follows:

2    |- src
3        |- ToDoListComponent
4            |- ToDoItemComponent.js
5            |- TextComponent.js
6            |- CheckComponent.js
7            |- ButtonComponent.js
8            |- index.js
9        |- actions.js
10        |- App.css
11        |- App.js
12        |- index.css
13        |- index.js
14        |- reducers.js
15        |- store.js
1// actions.js
3// These are our action types
4export const DELETE_ITEM = "DELETE_ITEM"
5export const PRINT_ITEM = "PRINT_ITEM"
9// Now we define actions
10export function deleteItem(itemIndex){
11    return {
12        type: DELETE_ITEM,
13        itemIndex
14    }
17export function printItem(itemIndex){
18    return {
19        type: PRINT_ITEM,
20        itemIndex
21    }
24export function togglCheck(itemIndex){
25    return {
26        type: TOGGLE_CHECK,
27        itemIndex
28    }
1// reducers.js
3import { DELETE_ITEM, PRINT_ITEM, TOGGLE_CHECK } from './actions';
5const initialState = {
6    tasks: [
7        {
8            label: "Task 01",
9            isCheckItem: false,
10            hasActions: false,
11            isChecked: false
12        },
13        {
14            label: "Task 02",
15            isCheckItem: true,
16            hasActions: false,
17            isChecked: true
18        },
19        {
20            label: "Task 03",
21            isCheckItem: false,
22            hasActions: true,
23            isChecked: false
24        },
25        {
26            label: "Task 04",
27            isCheckItem: true,
28            hasActions: true,
29            isChecked: false
30        }
31    ]
34export default function todoReducer(state, action) {
35    if (typeof state === 'undefined') {
36        return initialState
37    }
39    switch(action.type){
40        case DELETE_ITEM:
41            console.log("deleting");
42            break;
44        case EDIT_ITEM:
45            console.log("editing");
46            break;
48        case TOGGLE_CHECK:  
49            var items = [...state.tasks];
50            items[action.itemIndex].isChecked = !items[action.itemIndex].isChecked;
51            state = {...state, tasks: items};
52    }
54    // We create an empty reducer for now
56    return state
1// store.js
3import { createStore } from 'redux'
4import todoReducer from './reducers'
6export default createStore(todoReducer)
1// ViewPageComponent.js
3import React, { Component } from 'react';
4import { connect } from 'react-redux'
5import TodoListComponent from './TodoListComponent';
6import { deleteItem, printItem, togglCheck } from './actions';
8class ViewPageComponent extends Component {
9  render(){
10    return (
11        <TodoListComponent 
12          itemList={this.props.items} 
13        />
14    );
15  }
18function mapStateToProps(state) {
19  return {
20      items: state.tasks
21  }
24const mapDispatchToProps = {
25  deleteItem,
26  printItem,
27  togglCheck
30export default connect(mapStateToProps, mapDispatchToProps)(ViewPageComponent);
1// App.js
3import React from 'react';
4import { Provider } from 'react-redux'
5import store from './store';
6import ViewPageComponent from './ViewPageComponent';
8function App() {
9  return (
10    <Provider store={store}>
11      <ViewPageComponent />
12    </Provider>
13  );
16export default App;

Note that the ViewPageComponent is already connected to the Redux store and actions. Let's take a moment to analyse the data structure we used in the reducers.

For the context of this guide, we assume that all data has already been fetched and stored in the tasks state in the reducer. Further, the app will only show the tasks and will not handle inserting new tasks to the list.

Observing the tasks array in reducers.js, we can identify the four types of tasks we have to render from our component:,

  1. Task 01 - text only item
  2. Task 02 - checkbox item
  3. Task 03 - text item with action buttons
  4. Task 04 - checkbox item with action buttons

Also we pre-defined two actions:

  1. Delete Item action - this will remove the current items from the task list
  2. Print Item action - this will simply print the task text to console out

With these in mind, let's continue in our journey.

Building the Text-only Todo

The first version of the app will display "text" items only. This will let us build the core components of the app which then can be extended. We wil start with TextComponent. Right now, we need to determine if this component needs direct access to the store. Going with the traditional thought process, we will model TextComponent as a dumb component and will pass any property required to dsiplay content using props.

The traditional thought process around connecting with redux store has two general pieces of advice (1) Minimize the spread of Redux connectivity in the app, ie: to concentrate on a few components when possible; (2) To give the connectivity to components higher in the hierarchy. Both of these are helpful in general, except when the situation requires more finesse.

1export default function TextComponent({ itemId, itemText }){
2    return (
3        <div className="list-item-text">
4            <span>{itemText}</span>
5        </div>
6    )

With that done, we will create the ToDoItemComponent. Again, we will be going with the strategy that the store connectivity is to be in the highest level. So, any property is to be passed through props.

1import TextComponent from "./TextComponent";
3export default function({ item }){
4    return (
5        <div className="list-item">
6            <TextComponent 
7                itemId={} 
8                itemText={item.label}    
9            />
10        </div>
11    )

Finally, we create the TodoListComponent (in the index.js). Still, the component won't be interacting directly with the React store or actions. The necessary information, ie: the list of items, will be passed from the parent component. Also, we will add this component to the ViewPageComponent and pass the item list to it, so we can verify that everything works up to that point.

1// TodoListComponent/index.js
3import React from 'react';
4import ToDoItemComponent from "./ToDoItemComponent";
6export default function TodoListComponent({itemList}){
7    return (
8        <div className="todo-list">
9            {, idx) => (
10                <ToDoItemComponent item={item} key={idx} />
11            ))}
12        </div>
13    )
3// ...
5class ViewPageComponent extends Component {
6  render(){
7    return (
8        <TodoListComponent itemList={this.props.items} />
9    );
10  }
13// ...

If you run it and test, it should show the items. All good.

Extending Todo: Adding checkbox Item

Next, we will add checkbox items. This should be easy. First, we create the CheckComponent and then modify the TodoItemComponent to reflect the check items. Now the problem arises, where should we put the checkbox toggle action? Let's go with the current pattern and pass on the toggle action right from the highest in the hierarchy: ViewPageComponent.

1// CheckComponent.js
3import React from 'react';
5export default function CheckComponent({itemId, itemText, isChecked, toggleItem}){
6    return (
7        <div className="list-item list-item-text">
8            <input 
9                type="checkbox" 
10                onChange={() => toggleItem(itemId)} 
11                checked={isChecked} 
12            />
13            <span>{itemText}</span>
14        </div>
15    )
3import React from 'react';
4import TextComponent from "./TextComponent";
5import CheckComponent from './CheckComponent';
7export default function({ item, itemId, togglCheck }){
8    return (
9        <div className="list-item">
10            { item.isCheckItem ? (
11                <CheckComponent
12                    itemId={itemId}
13                    itemText={item.label}
14                    isChecked={item.isChecked}
15                    toggleItem={togglCheck}
16                />
17            ) : (
18                <TextComponent 
19                    itemId={itemId} 
20                    itemText={item.label}    
21                />
22            )}
23        </div>
24    )
1// index.js
3import React from 'react';
4import ToDoItemComponent from "./ToDoItemComponent";
6export default function TodoListComponent({itemList, togglCheck}){
7    return (
8        <div className="todo-list">
9            {, idx) => (
10                <ToDoItemComponent 
11                    item={item} 
12                    itemId={idx}
13                    key={idx} 
14                    togglCheck={togglCheck}
15                />
16            ))}
17        </div>
18    )
3// ...
4class ViewPageComponent extends Component {
5  render(){
6    return (
7        <TodoListComponent 
8          itemList={this.props.items} 
9          togglCheck={this.props.togglCheck}
10        />
11    );
12  }
14// ...

As we can quickly observe, to add just the CheckComponent to the hierarchy, we had to create changes in three other components. The reason being, to pass on the actions from the top most component to the lowest component. The toggleCheck action is passed from ViewPageComponent to TodoListComponent to TodoItemComponent and, finally. to CheckComponent to be used.

Let's take a moment and think about if this is scalable in the future. We are yet to add the action button components, and this would require adding changes to three other layers in the hierarchy. At this point, we need to make a decision about changing our architecture to better adapt to changes.

Thinking Process

Moving Actions to CheckComponent

We'll start thinking from the very bottom layer. What if we connect the CheckComponent directly to the store? Then, once we create the ButtonComponent, we would not need to modify two other unnecessary files. But the focus is to make it robust, overall. This is not a bad option, but it lowers the overall maintainability. Having Redux connections at one point is preferred, if possible. Having each component connecting itself to Redux will reduce adaptability in the long run.

Moving Actions to TodoItemComponent

In comparison to the previous option, this is an improvement. Every new component doesn't need to be connected to the store and TodoItemComponent can act as the intermediate. Still, it will require a component higher in the hierarchy to retrieve the task list from the store, which means another component needs to be connected to the store. So, we must brainstorm further.

Moving Actions and Store Access to TodoListComponent

If we simply move all Redux connectivities to TodoListComponent, it could retrieve the task list, rather than getting it through the ViewPageComponent, and only will need to remove one layer for modifications when passing the actions to the bottom layer component. This seems like the ideal choice, yet it still requires passing down actions several layers below to bottom-level components.

Hybrid Method: Segregating the redux Connectivities

A hybrid method seems ideal for the scenario. We could move the store access to TodoListComponent while keeping the action connectivities at TodoItemComponent. This essentially creates two places where Redux connections occur, but it retains the overall maintainability and makes it easy to scale. Let's change the overall code to reflect this change.

The completed code is available in the Github repo (since the code is repetitive work, it is not added into the guide). Take time to read through the code to observe the benefits gained by moving to our hybrid architecture.


An important update on this matter is the introduction of Redux Hooks, in the recent release of Redux. Hopefully the adaption will be explained in a future guide.

In conclusion, the key takeaway is that structuring your component hierarchy and the Redux connectivities is a subjective matter. There will be no concrete rules to select the perfect option. But in general, following the rules of traditional pattern will give you a better foundation to start.