Efficiently computing derived data from react props

2.4k views Asked by At

We are in the process of implementing performance optimizations in our react/redux application. Part of those optimizations included introducing reselect. This worked nice for data that is derived directly from the state. but what about data that is derived from other props?

Example:

We have 3 components Feed FeedItem and Contact (Contact is a component for displaying a users contact information).

a FeedItem gets an object that represents an item in the feed, one of the properties of a feed item is an actor object. This object is like a user but a bit different (this sucks but can't be changed). This means that if I want to render a Contact for this actor I need to create a new object that maps the properties from an actor to a user. Creating a new object on every render is a performance anti pattern because we are using shallow equality checks.

e.g code:

<Contact
  user={{
    photoUrl: actor.photo.smallPhotoUrl,
    Id: actor.id,
    Name: actor.name,
  }}
</Contact>

Is there a pattern for solving this? reselect only supports derived data from redux state, this is basically derived data from props.

1

There are 1 answers

6
Jim Bolla On BEST ANSWER

You can pass whatever you want to reselect's selector methods. It doesn't have to be state and props. That just happens to be it's most common use case. You can call one if it's generated selectors with any number of arguments.

Here's one way you could use it:

function convertActorToContactUser(actor) {
  return {
    photoUrl: actor.photo.smallPhotoUrl,
    Id: actor.id,
    Name: actor.name,
  };
}

class ActorContact extends Component {
  constructor(...args) {
    super(...args);
    this.getUser = createSelector(
      () => this.props.actor,
      convertActorToContactUser
    );
  }

  render() {
    return <Contact user={this.getUser()} />
  }
}