Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why React.memo and shouldComponentUpdate aren't doing the same?

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?

like image 202
Bob van 't Padje Avatar asked Aug 31 '25 01:08

Bob van 't Padje


1 Answers

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

like image 82
Dupocas Avatar answered Sep 02 '25 15:09

Dupocas