When users think of using Redux, they generally use it with React even though there are implementations for angular and other SPA frameworks. One of the concepts to get used to is having a global store and accessing that store inside of your React Components. Luckily we have an npm package that helps us integrate Redux with React called react-redux. You can also check out some of our video courses for more in-depth coverage.

Connecting Redux To React Components

There is a special package specifically for connecting your redux store to you React. React-redux.  You must import this into any component that you will connect to redux.

import { connect } from 'react-redux';

You will then have access to 3 functions. Connect, mapStapteToProps and mapDispatchToProps. Connect is a higher order function that takes in both mapStateToProps and mapDispatchToProps as parameters.

export default connect(
    mapStateToProps, 
    mapDispatchToProps
)(TodoList);

Using MapStateToProps

In React, MapStatetoProps pulls in the state of a specific reducer state object from you global store and maps it to the props of your component. MapStateToProps is called everytime your store is updated. You pass in your state a retrieve that specific objects from the reducer.

const reducers = combineReducers({
    todoReducer: todoReducer,
    form: formReducer
});
export default reducers;
const mapStateToProps = (state, ownProps) => {
    console.log(state);
    return {
        todos: state.todoReducer.todos
    }
};

Using MapDisptachToProps

MapDispatchToProp takes the dispatch functions in your component and executes them against the Redux Reducer when that function is fired. Remember that Props aren’t just objects, they can also be functions. This is where MapDispatchtoProps applies. MapDispatchToProps allows for you to dispatch state changes to your store. An example would be a button click that triggers a refresh or an automatic loading of data once the component is mounted.

const mapDispatchToProps = dispatch => ({
    getAllTodos: () => dispatch(getAllTodos)
});

Using MapDispatchtoProps and MapStateToProps Together

In this example, you can see both MapDispatchtoProps and MapStateToProps used together.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { loadTodos, createTodo, deleteTodo } from '../../services/todoService';
import TodoItem from './TodoItem';
import { ListGroup, ListGroupItem, Button } from 'reactstrap';
import { getAllTodos } from './todoReducer';

export class TodoList extends Component {
    constructor() {
        super();

    }

    componentDidMount() {
        this.props.getAllTodos();
    }
    render() {
        const { match, loading, todos } = this.props;
        console.log(this.props);
        return (
            <div>
                {
                    loading && (
                        <p><em>Loading...</em></p>
                    )}
                {
                    !loading && (
                        <div>
                            <h1>All Todos</h1>
                            <a className="btn btn-primary btn-lg btn-block active" role="button" aria-pressed="true" href={'/todos/create'}>Create</a>
                            <ListGroup>
                                {todos.map((todo) =>
                                    <TodoItem key={todo.id} todo={todo} />
                                )
                                }
                            </ListGroup>

                        </div>
                    )
                }
            </div>
        )
    }
}

const mapStateToProps = (state, ownProps) => {
    console.log(state);
    return {
        todos: state.todoReducer.todos
    }
};

const mapDispatchToProps = dispatch => ({
    getAllTodos: () => dispatch(getAllTodos)
});

export default connect(
    mapStateToProps, 
    mapDispatchToProps
)(TodoList);

Then once the component is mounted, that new state is accessible by it’s props and then I can loop through it to display each element in order.

Conclusion

Using mapDispatchtoProps and mapStateToProps is used heavily in React and Redux development. It’s a simple concept when once learned allows for you to control which components have access to data and reusable dispatch actions. If you’re interested in learning more, check out some of our courses here.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit