Reusability
Selectors promote reusability and composability by allowing developers to compose complex data transformations from simpler selectors. By building selectors as composable functions, you can create reusable building blocks that can be combined to derive various pieces of data from the store. This modular approach simplifies code maintenance and promotes code reuse across different parts of your application.
// Composable Selectors
const selectUsers = state => state.users;
const selectActiveUsers = createSelector(
selectUsers,
users => users.filter(user => user.isActive)
);
const selectActiveAdminUsers = createSelector(
selectActiveUsers,
users => users.filter(user => user.role === 'admin')
);
Why are selectors considered best practice in React Redux ?
Redux selectors are functions that allow for efficient and structured extraction of specific data from the Redux store. They can calculate derived data, which helps Redux maintain the minimum possible state. Selectors are also efficient, as they are only recomputed if any of their arguments change.