React Core & Hooks (407 Qs)•Part 7: Supported Libraries, Styling & Integrations (139 - 151)
What is reselect and how it works?
junior LevelCode ExamplereactSupported Libraries
Reselect is a memoized selector library for Redux (built into Redux Toolkit) that prevents expensive recalculations and unnecessary component re-renders.
Core Benefits
- Memoization: Selectors compute derived state and cache results based on input selectors.
- Referential Stability: Returns the cached object reference if inputs haven't changed, preventing re-renders.
- Composability: Selectors can be chained together into modular data retrieval pipelines.
Code Example
javascript
import { createSelector } from '@reduxjs/toolkit';
const selectCartItems = (state) => state.cart.items;
const selectTaxRate = (state) => state.cart.taxRate;
// Memoized selector: only runs when selectCartItems or selectTaxRate changes
export const selectCartTotal = createSelector(
[selectCartItems, selectTaxRate],
(items, taxRate) => {
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
return subtotal * (1 + taxRate);
}
);