In the React-Redux, mapDispatchToProps
is a function that connects Redux actions to React props. It allows mapping between Redux action creators and component props so that components can dispatch Redux actions without knowing anything about Redux.
The mapDispatchToProps
function can be used in the following ways:
Object shorthand notation
Function notation
In this notation, actionCreator
is an action creator function that returns an action object.
const mapDispatchToProps = {actionCreator}
The mapDispatchToProps
function maps this function to a prop with the same name (actionCreator
) and passes it to the connected component. When the prop is called, it automatically dispatches the corresponding action.
In this example MyCounter
component is defined. It takes two props: value
and inc
. It maps the value
prop to the value from the Redux store, and inc
to a function that dispatches an incrementCounter
action to the Redux store.
Below is the implementation of this example using object notation.
In this notation, mapDispatchToProp
takes the dispatch
function as a parameter.
const mapDispatchToProps = (dispatch) => {return {action: () => dispatch(actionCreator())}}
In this example, MyCounter
component is defined. It takes two props: value
and inc
. It maps the value
prop to the value from the Redux store, and inc
to a function that dispatches an incrementCounter
action to the Redux store.
Below is the implementation of this example using function notation.
Object shorthand notation works well if we only need to map one or two action creators to the component props. However, function notation provides more control over the mapping, such as calling multiple action creators or passing arguments to the action creators.
Free Resources