arrow_back When can I use the second parameter in useSelector?

1 vote
I know that useSelector takes the second optional parameter and I would like to know in which cases I can use it ?

1 Answer

Best answer
0 votes
For example, you have a selector like this
const selector = (state) => {
return {
a: state.a,
b: state.b,
as you can see, it always returns a new value because a new object (new reference). If the selector returns, for example, {a: 1, b: 2}, the component in which useSelector is called will always be re-rendered, since useSelector compares the old and new values by reference by default and therefore considers them different. second parameter, you can plug in a function that can compare objects more "thoughtfully" and recognize them as the same, even if the references are different:
const isEqual = (x, y) => {
return x === y || (x.a === y.a && x.b === y.b);
This way we can save renders.

you can take a ready-made shallowEqual from 'react-redux' if only a surface comparison, or use a deep comparison or something else.