Friday, August 14, 2020

mapStateToProps in Redux

The is a function which takes the state as an input parameter and maps the properties in the state to props mapStateToProps  in the component.

mapStateToProps take the state object (the same value returned by a call to store.getState()) as the first argument and return a plain object containing the data that the connected component needs.  This function should be passed as the first argument to connect, and will be called every time when the Redux store state changes.
The mapStateToProps acts as a filter, it takes the full status and filters out only the props required for the component. Without mapStateToProps the full state will have to be passed to the component many of the properties in the state will not be used by the component, mapStateToProps filters out unwanted properties and maps only required properties to component level props.

In the below script the mapStateToProps function maps only 2 properties name & greeting from the redux state to component-level properties.

function mapStateToProps(state) {
  return {
    name: state.homeReducer.name,
    greeting: state.homeReducer.greeting
  };
}

Much like a Redux reducer, a mapStateToProps function should always be pure and synchronous. It should only take state and return the data the component needs as props without mutating those arguments. It should not be used to trigger asynchronous behavior like AJAX calls for data fetching.

React Redux decides whether the contents of the object returned from mapStateToProps are different using === comparison (a "shallow equality" check) on each fields of the returned object. If any of the fields have changed, then the component will be re-rendered so it can receive the updated values as props.

For this reason we should use mapStateToProps to filter out only properties which are required by the component so that the number of re-render of the component are minimal thereby improving the performance of the Component and application.
mapStateToProps Is the first parameter to the connect which connects react and redux.

export default HomeReduxContainer = connect(mapStateToProps, mapDispatchToProps)(HomeRedux); 

Search Flipkart Products:
Flipkart.com

No comments: