How to limit react-redux connect update re-renders to specific state branches?

后端 未结 3 1144
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 18:06

I have an action and reducer that updates a global counter. This action is fired on a rapid interval. The reducer returns a new copy of the state for each action. The reduce

相关标签:
3条回答
  • 2020-12-10 18:50

    According to Redux implementation, connect is pure and hence does a shallow comparison of the props that it needs to provide to the component i.e it implements a shouldComponentUpdate method in its implementation and doesn't trigger a re-render for the connected component if the data returned from mapStateToProps doesn't change.

    It is important for Redux to monitor the state change for every change because then only it can take a decision whether to update or not.

    Since a Pure component does a shallow comparison of state and props, you should make sure that your states are not highly nested

    0 讨论(0)
  • 2020-12-10 18:58

    Redux connect accepts a areStatesEqual function option that can be used to narrow down equality checks to specific state branches.

    export default connect(
      {},
      {},
      null,
      {
        areStatesEqual: (next, prev) => {
          return (
            prev.branch === next.branch
          );
        }
      }
    )(Component);
    
    0 讨论(0)
  • 2020-12-10 19:07

    If it is a performance issue due to redux, use react shouldComponentUpdate method.

    https://reactjs.org/docs/react-component.html#shouldcomponentupdate


    Update: CombineReducers would make a difference. Try changing

    return {
       ...state,
       loop: action.payload,
    }
    

    to

    state.loop = ...action.payload;
    return state;
    

    If you don't want to mutate the state, you should use combineReducer with loop as its own reducer. Since you weren't using combineReducers, I turned the state into the rootReducer. Its similar to what the redux author does with combineReducers (video) with the exception that the nextState was created within the combineReducer.

    0 讨论(0)
提交回复
热议问题