Blog>
Snippets

Refactoring Redux Selectors

Exhibit how to refactor Redux selectors to work with specifically-typed state and actions instead of using AnyAction.
// Define State and Action Types

type AppState = {
  user: {
    name: string;
    age: number;
  };
  // ...other state properties
};

type UserAction = |
  { type: 'SET_USER_NAME'; payload: string; } |
  { type: 'SET_USER_AGE'; payload: number; };
  // ...other user-related actions

type AppAction = UserAction; // | OtherAction; For additional action types

// Refactored Selector

const selectUserName = (state: AppState): string => state.user.name;

// Usage of the Selector in a component

// mapStateToProps with UserType
const mapStateToProps = (state: AppState) => ({
  userName: selectUserName(state), // Utilizing the specifically-typed selector
});
The code defines specific TypeScript types for the AppState and actions related to the user (UserAction). Then it creates a typed selector function (selectUserName), avoiding the use of the 'any' type. The state passed to the selector is typed, ensuring that only valid properties are accessed and returned. Finally, we demonstrate the use of the new specifically-typed selector in a mapStateToProps function, which is used to pass state as props to a React component.