Autoplay

    Redux: Using mapDispatchToProps() Shorthand Notation

    Dan AbramovDan Abramov

    We will learn how to avoid the boilerplate code in mapDispatchToProps() for the common case where action creator arguments match the callback prop arguments.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:01 The mapDispatchToProps function let's us inject certain props into the React component that can dispatch actions. For example, the TodoList component calls its on Todo click callback prop with the ID of the Todo.

    00:17 Inside mapDispatchToProps we specify that when on Todo click is called with an ID, we want to dispatch the toggle Todo action with this ID. The toggle Todo action creator uses this ID to generate an action object that will be dispatched.

    00:37 When the arguments for the callback prop match the arguments to the action creator exactly, there is a shorter way to specify mapDispatchToProps.

    00:48 Rather than pass a function, we can pass a special object, a map, in between the names of the callback props that we want to inject and the action creator functions that create the corresponding actions.

    01:03 This is a rather common case, so often you don't need to write mapDispatchToProps, and you can pass this map in object instead.

    01:12 Let's recap. Normally, mapDispatchToProps accepts the dispatch function as an argument so that you can return the props through inject into the React component that each can dispatch certain actions using the dispatch function.

    01:29 However, it is very common that the arguments passed through the callback props are passed through to the action creators in the same order. In this case, rather than write mapDispatchToProps function yourself, it can pass a configuration object that maps the names of the callback props to the corresponding action creator functions.

    Discuss

    Discuss