Components do not have access to all the data in the redux
store. They only have access to that data in the redux
store that is passed to them as props
.
As far as your question of what's the purpose of mapStateToProps
, is concerned, following are the main uses of mapStateToProps
:
- Tell
react-redux
what data any particular component needs.
- Transform the store state and pass the transformed state to the component as a prop
- Help
react-redux
decide whether a particular component should re-render as a result of store update.
Tell React-Redux what data component needs
mapStateToProps
function tells react-redux
what data a particular component needs from the redux
store. This function gets the whole state as an argument but the problem is that you can't access this inside the React
component. It is passed to mapStateToProps
function, not to your component. So you need react-redux
to pass the required data to your component as props
.
Transforming Store State
.mapStateToProps
function can also be used to transform the store state in such a way that is appropriate for any particular component, for example:
- Combining different pieces of state from different parts of the store.
- Passing a data as a specific prop name
- Transforming data in any way that is appropriate for use by the component.
Help React-Redux decide whether a particular component should be re-rendered
Now you might ask, what if i tell react-redux
to pass whole state
argument to my component as a prop
?
Problem with doing this is that whenever the state in the redux
store updates, your component will re-render even if it didn't use any part of the state that changed.
This behavior is caused by how react-redux
uses mapStateToProps
function to decide whether a component should be re-rendered as a result of store's state update.
Whenever redux
store updates, react-redux
does a shallow comparison (===
) of each field of the object returned by mapStateToProps
function and if any of the field is different, your component will be re-rendered.
To prevent this behavior, you use mapStateToProps
function to only get that data that is actually used inside the component. This way, if any un-related data is updated in the redux
store, it won't cause a re-render of your component.
For more details of mapStateToProps
function, see:
React Redux: Extracting Data with mapStateToProps