Selecting State with Typed Selectors
Provide a code example for creating and using typed selectors with Redux's useSelector hook to ensure the selected state fragments are properly typed.
import { createSelector } from '@reduxjs/toolkit';
import { useSelector } from 'react-redux';
// Define the state type
interface RootState {
users: {
list: string[];
isLoading: boolean;
};
}
// Selector to get the users list
const selectUsersList = (state: RootState) => state.users.list;
// Selector to get the loading state
const selectIsLoading = (state: RootState) => state.users.isLoading;
// Using createSelector to create a memoized selector
const selectUserCount = createSelector(
selectUsersList,
(list) => list.length
);
This example shows how to use the createSelector function from the @reduxjs/toolkit package to create typed selectors for different parts of the state. It provides typed access to user list and loading states, as well as a derived state (user count) which is memoized for performance.
function UserList() {
// Use useSelector hook with the typed selector
const users = useSelector(selectUsersList);
const isLoading = useSelector(selectIsLoading);
const userCount = useSelector(selectUserCount);
// ...component logic
}
This example demonstrates how to use the typed selectors within a React functional component using the useSelector hook. It ensures that the state fragments (`users`, `isLoading`, `userCount`) are properly typed when they are being used within the component.