1

I created a react project using redux as state management. I have two different states stored in the same reducer and used by two different components. But every time I change the state in one component, the other component also re-rendered. How to prevent this rendering behavior?

You can try my sandbox here: https://pjm8e.csb.app/

I put some console.log inside each component, and both are rendered when the button clicked

1 Answers1

2

This is happening, because both of the components are connected to the whole state. So if you update only a small part of the state, it causes them both to rerender. You can use hooks for dispatch and selectors to only connect to relevant parts of the store. Here is a sandbox example:

https://codesandbox.io/s/shy-architecture-1n0g7?file=/src/Consumer2.js

szczocik
  • 1,293
  • 1
  • 8
  • 18
  • It works! So it's not necessary to use connect() from redux? – Luthfi Hizbulloh Oct 02 '20 at 09:05
  • You can use either ```connect``` or hooks. Since everyone is now using hooks, I would recommend this approach. If you would prefer connect, you can still have the same result, but you will have to map only a subset of the state in you ```mapStateToProps``` – szczocik Oct 02 '20 at 09:07