Search code examples
reactjsreact-nativereduxreselect

React class instance prop prevents from using PureComponent


My React component has a prop that is a class instance based from data coming from the redux store.

The reason for this is that it is much more convenient to deal with this data using a class and all its custom methods (more than 50).

I cannot use PureComponent as React always consider that this prop has changed. The problem is that most of my React components are connected to this prop...

I am aware of solution like reselect but this would mean having too many (as many as my class has custom methods) selectors only for the manipulation of this data.

What would you suggest?

My redux select looks like this:

getStation(state) {
  // some logic to fetch the right station
  return new WeatherStation(state.services.stationList[i])
}

where WeatherStation is:

class WeatherStation {
  constructor (data) {
    this.station = data
  }

  getId() {...}
  // many more methods
}

and within my React Compoonent:

class MyComponent extends React.Component {
  ...
  const mapStateToProps = (state, ownProps) => {
    return {
      station: getStation(state),
    }
  }
}

Solution

  • Have you tried using reselect along these lines?

    import { createSelector } from 'reselect';
    
    getStationData(state) {
      // some logic to fetch the right station
    
      // no new instances here, just selecting the relevant data
      return state.services.stationList[i];
    }
    
    
    // create "memoized" selector. 
    const getEnhancedStation = createSelector(
      getStationData,
      stationData => new WeatherStation(stationData)
    )
    

    If I understand reselect and createSelector correctly, then this should generate a new WeatherStation instance only if the underlying data, ie. the thing returned from getStationData, has changed. (Instead of generating a new instance each time anything in the state changes.)