Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access state property inside mapStateToProps

I need to access specific properties of the redux state inside my containers. These properties will in turn be used as a key to fetch other nested properties and map them to component props. I use immutableJS.

Is the best way to do this inside the mapStateToProps? Will this cause any performance overhead or is it OK since the mapStateToProps already receives the whole state as a parameter?

Here is an example.

state selectors:

export const userSettingsState = state => state.get('userSettings');
export const transactionsState= state => state.get('transactions');

userSettings is an immutable Map and transactions is also a Map of userID and transaction list pairs.

const mapStateToProps = (state) => {
  const curUID = userSettingsState(state).get('currentUserID');
  return {
    trList: transactionsState(state).getIn([curUID, 'trList'])
  };
};

I need the currentUID to access the user transactions. The above sample works fine. But is it the best way?

like image 486
empyreal Avatar asked Nov 09 '22 00:11

empyreal


1 Answers

Great question. Yes, this is the preferred way to handle computed props and to generate derived data. Not only is this the best way, but it's also very performant. Cory House (a very good React dev well known in the community) tweeted about something similar to this a few days ago and his same methodology applies to mapStateToProps(). Your only other option is to add a compute method to componentWillReceiveProps() AND componentDidMount(). This get's messy fast as you could imagine.

Now, some reservations about the way you're doing this.

Don't put async calls in here! This will also cause issues with rendering components as mapStateToProps() runs before the component mounts. If your component is waiting for promises before it mounts, you're going to take performance hits. This is probably obvious.

Speaking of performance, I am personally generating derived data exactly like this for a dropdown box with 8,600 entries that on user input, applies a fuzzy filter to those 8,600 entries, re-renders the dropdown list, and displays a new filtered list. There have been zero performance issues and the component is smooth as butter.

like image 196
daHolby Avatar answered Dec 30 '22 04:12

daHolby