gajus / redux-immutable

redux-immutable is used to create an equivalent function of Redux combineReducers that works with Immutable.js state.
Other
1.88k stars 82 forks source link

selectLocationState function appears to cause render without state change #43

Closed ghost closed 7 years ago

ghost commented 7 years ago

I noticed the other day that my entire app was being rendered more frequently than expected. I eventually tracked this down to the Router component, which seemed to be rendering on every new action. I think the cause of this may be the selectLocationState function described in the docs, which invokes toJS on the routing state subtree. As I understand it, this creates a new JavaScript object every time the function is called, which is not equal to the previous object even if it contains the same data, causing React to re-render the Router. I tried replacing this with a memoized function that would return an identical object for the same state, and this appeared to fix the problem:

const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (function () {
    let prevState;
    let prevStateJS;
    function selectLocationStateHelper(state) {
      const newState = state.get('routing');
      if (!newState.equals(prevState)) {
        prevState = newState;
        prevStateJS = newState.toJS();
      }
      return prevStateJS;
    }
    return selectLocationStateHelper;
  }()),
});

Does it make sense to do something along these lines?

gajus commented 7 years ago

Refer to https://github.com/gajus/redux-immutable/pull/33.