0

What is the best practice for performing equality checks with the react-redux useSelector hook? Should you always use something like deepEqual from react-fast-compare when you are expecting a reference data type back to prevent unnecessary rerenders?

Example:

const myStateObj = useSelector(state => state.myStateObj, deepEqual)
DanB-Web
  • 33
  • 1
  • 6

1 Answers1

1

That equality check is almost always more expensive than the rerender.

Let's put it like this: if that would be a best practice, it would be the default and you would not have to add it. The best practice is to use multiple useSelector calls, select exactyle the data you need (without creating new objects in the selector) and not add any comparison function at all.

You can read more info on this here in the Redux Style guide

phry
  • 35,762
  • 5
  • 67
  • 81
  • Thanks for the response, makes sense. Does that also apply to components high up the state tree that may trigger multiple child rerenders? – DanB-Web Jan 28 '22 at 20:39
  • 1
    If you subscribe to a minimum amount of data your component actually needs to display it does not matter what kind of equality comparison you use. Your component will need to rerender if that data changes. – phry Jan 28 '22 at 23:22