Defining and Using Typed Selectors
Illustrate the use of createSelector from Reselect with TypeScript to create type-safe selectors that can derive data from the Redux store state.
// Define the state shape
interface State {
user: {
name: string;
age: number;
};
products: {
items: Array<{ id: number; name: string }>;
};
}
// Define a simple selector
const selectUser = (state: State) => state.user;
// Define a selector with Reselect, that derives data from the state
import { createSelector } from 'reselect';
const selectUserName = createSelector(
selectUser,
(user) => user.name
);
const selectUserAge = createSelector(
selectUser,
(user) => user.age
);
This code defines a `State` interface which encapsulates types for `user` and `products`. It then defines simple selectors to extract `user` from the state. After that, it uses `createSelector` from `Reselect` to create derived selectors for the `name` and `age` of the `user`, providing type safety by using those selectors.
// Define a product selector
const selectProducts = (state: State) => state.products.items;
// Define a memoized selector to get all product names
const selectProductNames = createSelector(
selectProducts,
(products) => products.map((product) => product.name)
);
This code snippet showcases how to define a typed selector for `products` within the state. It then uses the `createSelector` function to derive and map through all product names, creating a memoized selector for optimized performance.
// Usage example within a React component
import { useSelector } from 'react-redux';
function UserDetails() {
const userName = useSelector(selectUserName);
const userAge = useSelector(selectUserAge);
const productNames = useSelector(selectProductNames);
// ... render or use the selected data
}
This code example demonstrates how to use the typed selectors `selectUserName`, `selectUserAge`, and `selectProductNames` within a React component using the `useSelector` hook from `react-redux` to access type-safe data from the Redux store state.