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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With