4

I have a functional component which has has a connection to an object in my Redux store. To avoid re-renders when the object has changed I added React.memo, however, this didn't avoid the re-renders. My Memo looks something like this:

const MemoizedRadio = React.memo(Radio, (prevProps, nextProps) => {
  if (prevProps.selected !== nextProps.selected) {
    return false;
  }
  return true;
});

const mapStateToProps = state => ({
  nodes: state.canvas.elements.nodes
});

export default connect(mapStateToProps)(MemoizedRadio);

I would expect this component to not re-render if the nodes object has changed, but it does.

When I rewrite my component to a class component and add a shouldComponentUpdate the re-render will be prevented as expected. The shouldComponentUpdate looks as followed:

shouldComponentUpdate(nextProps) {
    if (this.props.selected !== nextProps.selected) {
      return true;
    }
    return false;
  }

I thought that React.memo acted the same as shouldComponentUpdate but this does not seem to be the case. The React.memo implementation does always re-render when the reference to the nodes object changes while the shouldComponentUpdate implementation prevents the re-render as expected.

Can anyone explain this behaviour?

3
  • 1
    Quick tip: return prevProps.selected !== nextProps.selected is already a boolean! Commented Jul 8, 2019 at 16:44
  • hmm this all seems fine at a glance, why isn't selected part of the props? Also, just out of curiosity, but why would you pass nodes as props but aren't interested in re-rendering if they change? Commented Jul 8, 2019 at 17:01
  • @James This was just to show some easy example code. I'm rendering a canvas which contains a lot of nodes. Each node can also have children, which are different nodes. The node has a child property which is just the id of the child node. So, to populate the content in the childNode I need to access all my nodes and populate the content with the correct values. Commented Jul 9, 2019 at 8:18

1 Answer 1

3

You are using React.memo correctly, the problem is that you are using connect an HOC to connect class based components to the store. Instead of using HOC you should use useDispatch and useSelector

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'm gonna upgrade react-redux to make it work with hooks and see if that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.