Accessing parts of the global state with mapStateToProps

mapStateToProps receives the complete state as a first parameter and the ownProps of the component as a second parameter. These props might be passed to the HOC. Depending on whether only the first or both parameters are passed, the function is either called if something changes within the Redux state or if the props change, which is passed to the component. It takes the following form:

const mapStateToProps = (state, ownProps) => {
  // ...
};

The function will always expect an object return value. The properties of this object will then be passed to the component as stateProps.

ToDo example

We would now like to pass pre-filtered todos based on their status and the overall number of todos to the component.

This would result in a mapStateToProps function which looks like this:

const mapStateToProps = (state) => {
  return {
    openTodos: state.todos.filter((todo) => todo.completed !== true),
    completedTodos: state.todos.filter((todo) => todo.completed === true),
    totalCount: state.todos.length,
  };
};

Passing mapStateToProps to the connect() function

The properties of this object such as openTodos, completedTodos, and totalCount will be passed to the wrapping component as props. How? By passing mapStateToProps to the connect() function. This will return a HOC, which we can then pass our component to (in which we access the props from the state):

const ConnectedTodoList = connect(mapStateToProps)(TodoList);

We’ve defined a ConnectedTodoList, which can now be used in JSX and be wrapped by a Provider component. It will render the TodoList with the given props from the global Redux store:

Get hands-on with 1200+ tech skills courses.