reactjsperformancereduxreact-redux

How does useSelector hook impact performance when selecting individual properties vs. destructuring the state in Redux?


I am using Redux in my React application and I often need to extract values from the Redux store using useSelector. Here are the two approaches I have considered:

Approach 1: Selecting individual state properties:

const username = useSelector((state) => state.user.username);
const userCart = useSelector((state) => state.user.cart);

Approach 2: Selecting the whole state and destructuring:

const { username, cart } = useSelector((state) => state.user);

I am concerned about the performance implications of these two approaches. Specifically, I am trying to understand:

Here is an example of my Redux slice:

const initialState = {
  username: '',
  cart: [],
  phoneNumber: '',
  address: ''
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // reducers here
  }
});

I expect that:

I read in the Redux documentation that Redux re-renders the component if the previous state is different from the current state, but I am unsure how this works in practice with the above approaches.

I am aware of libraries like reselect which are used to optimize state selection, but I do not want to consider them in this context.

Can someone please clarify the performance implications of these two approaches and recommend the best practice for extracting state from the Redux store?


Solution

  • You are correct.

    In approach 1, Redux knows that you are only using username and cart, and will therefore only rerender if one of those change.

    In approach 2, you are selecting the whole user slice, which means that the component will re-render if anything in it changes. The fact that you are destructuring it does not make any difference because it is "too late", Redux only knows that you are potentially using everything in user.

    So I would suggest you use approach 1 if you want to minimize the number of rerenders.

    On the other hand, approach 2 may be more readable and easier to maintain and an occasional rerender is usually very cheap (and how often do you expect phonenumber to change?), so unless you are dealing with expensive components or property changes several times a second, approach 2 would probably work just fine in many cases.