1. 13
    Use mapDispatchToProps Shorthand Syntax in Redux
    1m 42s

Use mapDispatchToProps Shorthand Syntax in Redux

Andy Van Slaars
InstructorAndy Van Slaars
Share this video with your friends

Social Share Links

Send Tweet

In this lesson we’ll take a mapDispatchToProps function and refactor it to use the available shorthand syntax to tidy our code up a bit.

[00:00] This approach to mapDispatchToProps is a pretty common pattern, and because of that, connect gives us a nice alternative to keep our code a bit more succinct. Rather than forcing us to wrap our action creator and dispatch calls manually, or with bindActionCreators like we're doing here, we can just pass in an object with our action creators and let connect handle that for us.

[00:19] I'm going to take this and I'm going to remove the function and the call to bindActionCreators and the reference to dispatch. I'm just going to let mapDispatchToProps be this object and let connect handle wrapping this and calls to dispatch.

[00:34] With that done I can jump to the top of the file and I can remove this import for bindActionCreators, because we're not going to use it anymore. Let's save the file. When the browser reloads, everything should still be working as expected, so we're good.

[00:50] While we're in here, let's refactor this a little bit. We've shortened up mapDispatchToProps. Our map state to props is fairly short, so we can take our connect and we can actually get rid of these extra definitions and we can just call connect like this.

[01:05] Then we can pass in our object as a second argument. Then we can just export default the result of calling connect, and get rid of that extra definition there. Then to make this a little bit more readable and easier to extend later, let's just break this onto multiple lines like so.

[01:33] Now, I'll save that and make sure I didn't break anything in the refactor. Everything looks good, and our form still works, and our todos still load.