reactjsreduxreact-reduxmemo

How to use React.memo with react-redux connect and set propsAreEqual?


I'm using react-redux and I have a component connected to it. my component has its own props (variants and functions) and also some state from store mapped with it, using mapStateToProps.

It's very important to us to manage when this component should re-render and for this purpose we're using propsAreEqual as a second argument to React.memo.

...

const mapStateToProps = (state: RootState) => ({
  name: state.user.name,
});

const dispatchProps = {
  editProfile: userActions.editProfile,
};

interface IProps {
  isOnCompleteProfile: boolean;
  onClickMessage: () => void;
}
type Props = ReturnType<typeof mapStateToProps> & typeof dispatchProps & IProps;

const MyFunction: React.FunctionComponent<Props> = (props) => {

   ...

}

function propsAreEqual(prevProps: IProps, nextProps: IProps) {
  return prevProps.isOnCompleteProfile === nextProps.isOnCompleteProfile;
}

export default connect(mapStateToProps, dispatchProps)(React.memo(MyFunction, propsAreEqual));

My question is, will this component re-render after state.user.name change in this scenario? or i have to mention prevProps.name === nextProps.name; in propsAreEqual too


Solution

  • Connect essentially wraps your component in a separate component (HOC) and renders your memoized component given the props from the mapStateToProps function.

    That being said, your memoized component will receive a prop called name. So you will have to return false in the propsAreEqual function in order for the component to update.