Is it more performant to useSelector() on an object vs the object's properties?

Viewed 243

Let's say we're working on our Customer Profile page with an object in the store called CustomerProfile.

export interface ICustomerProfileState {
    status: string,
    customerId: number,
    contactInfo: IContactInfo,
    financialInfo: IFinancialInfo
};

As we can see, this object consists of some plain properties as well as more complex ones. On the CustomerProfile.tsx page, let's compare two methods of tracking and updating the state of relevant properties. The first method is one where you useSelector on the individual state properties you want to track:

const status = useSelector((state) => state.customerProfile.status)
const preferredName = useSelector((state) => state.customerProfile.contactInfo.preferredName)
const altName1 = useSelector((state) => state.customerProfile.contactInfo.alternateName1);
const altName2 = useSelector((state) => state.customerProfile.contactInfo.alternateName2);
const preferredPayment = useSelector((state) => state.customerProfile.paymentInfo.preferredPaymentMethod;

Let's compare that with the second method -- simply tracking the object itself:

const customerProfile = useSelector((state) => state.customerProfile);

In the Redux documentation regarding hooks, specifically useSelector, it says:

When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.

This causes me to believe that the comparison above could amount to the same thing because the entire component will re-render whether one property changed or the entire object. But in our second method, where we useSelector(...state.customerProfile), I am making the assumption that we may needlessly re-render the component if irrelevant-to-the-component properties of customerProfile are updated elsewhere.

But maybe there is more happening under the hood with useSelector such that there is a performance difference between tracking individual properties on an object versus the entire object itself?

1 Answers

Performance is not a concern here. Either one will perform fine in any React application. Performance should be thought about after you have a working app and can do profiling. Identify the actual bottlenecks through profiling.

As for which style to use, use the one that is easiest to read and clearest to maintain. IMO a single selector with destructuring would be better. If profiling shows this to cause unnecessary re-rendering, then create separate selectors for each component of state and then one selector that uses those to put it back together in a single object so within the component there is still only one useSelector call.

Reusing and layering selectors with reselect is generally a best practice.

Related