Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

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

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 reducer looks like:

import { handleActions } from 'redux-actions';
import { sceneTick } from './actions';

export default (state, action) => handleActions({
  [sceneTick]: (state, action) => {
    return {
      ...state,
      loop: action.payload,
    }
  },

I am using react-redux's connect method on various React components. Not all the components care about this loop counter. Because I am returning a new state in the reducer on each tick, all components subscribed with connect get their mapDispatchToProps executed which causes unnecessary React render calls.

One of these componets looks like:

const mapStateToProps = (state, props) => {
  return {
    viewport: state.viewport,
    assets: state.assets,
  };
};


export default connect(mapStateToProps, {})(Component)

Even though this component has no dependency on state.loop it gets triggered to re-render. This causes re-rendering, over rendering, multiple rendering, unnecessary rendering, performance issues and unexpected behavior in components that need not re-render.

Update I should also maybe add that I am not using combineReducers here and all reducers are applied to the full state. Not sure if relevant.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...