What's the difference between mapStateToProps
and mapDispatchToProps
arguments to the connect
function in react-redux?
mapStateToProps vs mapDispatchToProps
42.2k views Asked by Lex V At
3
There are 3 answers
0
On
In a very simple term,
mapStateToProps: It connects redux state to props of react component.
mapDispatchToProps: It connects redux actions to react props.
A really light example: ( I hope, you know what I mean)
// state
const mapStateToProps = state => {
return { lists: state.lists };
};
// props
const mapDispatchToProps = ({ lists }) => (
<ul>
{
lists.map(el => (
<li key={ el.id }>
{ el.heading }
</li>
)
}
</ul>
);
// Now, connect state to prop
const List = connect(mapStateToProps)(mapDispatchToProps);
1
On
In very simple terms:
mapStateToProps
is called when you want to get the value of the global state from your component
function mapStateToProps(state) {
return {
message: state.message
};
}
The value of the global state is only changed with the help of an action. So if you want to change the value of global state you need an action. mapDispatchToProps
is used to bind action in your component.
mapStateToProps
is a function that you would use to provide the store data to your component, whereasmapDispatchToProps
is something that you will use to provide the action creators as props to your component.According to the docs:
A simple example would be