While using Redux, you may come across a situation where you are passing in props from both mapStateToProps and mapDispatchToProps, and using them together:
We can save Button having to know about name, and instead use mergeProps:
What does mergeProps do?
mergeProps is an optional third argument you can pass into connect. As the name suggests, it merges all the props into one object for your component to use. By default, it will look like this:
stateProps are all the props from mapStateToProps - in the above example, name
dispatchProps are all the props from mapDispatchToProps - setName
ownProps are all props that are passed into a component like this <Button foo={bar}/>
Accessing ownProps in mapDispatchFromProps
We can also access ownProps from mapDispatchToProps. Here we have the same Button example, but instead of name coming from mapStateToProps, this time it’s being passed in from the Form component:
We can use the name prop directly in mapDispatchToProps by using its second argument, ownProps:
Even if name is now unused, it will still be passed in as part of ownProps to the Button component. We can filter it out using mergeProps:
Pro-tip: Using mapDispatchToProps’ object form
You’ll notice that I always defined mapDispatchToProps in its function form:
If you’re not making use of ownProps or mergeProps, we can actually simplify it down to its object form, which does the exact same thing: