Why does the following use of useSelector break referential equality?

Viewed 23

I was having an issue where selecting certain values out of my store would trigger a rerender with any store value update, even if I was selecting values that weren't updating. It turns out, the issue was that I was doing this:

const transformedValues = useSelector(state => state.some.array).map(value => value);

As the answer to the above referenced question points out, this breaks referential equality of transformedValues, causing the component to update.

But when I do this, there is no issue, and no unecessary rerender:

const valuesFromStore = useSelector(state => state.some.array);
const transformedValues = valuesFromStore.map(value => value);

Why? What is the difference in these two tactics that in the first one, referential equality of the selector is broken (causing rerender), and in the second, it does not cause a rerender? What is going on "under the hood" of redux and javascript to make a difference here?

1 Answers

Hmm. That isn't a problem, and doesn't cause a new reference. useSelector(state => state.some.value) only causes a re-render when state.some.value itself changes.

I know you said in the other question that changing this fixed your issue, but based on what I can see there really shouldn't be any issue with that code in the first place.

Related