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:
If I change an unrelated state property (e.g., phoneNumber
) in the user
slice, will my component re-render in either or both approaches?
Which approach is more suitable for optimal performance in terms of minimizing unnecessary re-renders?
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:
username
or cart
changes.user
slice changes, even if the component does not use that property.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?
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.