Replace deprecated TypedUseSelectorHook with createSelectorHook for improved functionality

In my TypeScript code, I used the following to create a typed selector with Redux:

import { useSelector, TypedUseSelectorHook } from 'react-redux';

export interface RootState {
    user: {
        account: string;
    }
};

export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;

Recently, I learned that TypedUseSelectorHook is deprecated and should be replaced by

createSelectorHook<State, Action>()
.

I am unsure about how to make this change and whether Action needs to be included as well. Any ideas?

Answer №1

The useSelector hook has two generic variables: the type of the overall state (TState) and the type of the selected value (TSelected). Our goal is to create a bound hook where TState is fixed, but TSelected changes based on the selector argument we use with the hook.

TypedUseSelectorHook serves as a typescript override. Essentially, your useTypedSelector simply becomes useSelector.

In contrast, createSelectorHook works differently as it is a factory function that generates a useSelector hook. It accepts an optional context argument (docs link) and another generic variable for Action, as the context hinges on the action type. Since your selector hook does not rely on the action type, you can ignore this. The Action variable is optional and defaults to AnyAction. You only need to specify the generic for the state:

export const useTypedSelector = createSelectorHook<RootState>();

The type definition for useTypedSelector aligns with expectations, featuring a hook with just one generic representing the selected value:

const useTypedSelector: <Selected extends unknown>(
  selector: (state: RootState) => Selected, 
  equalityFn?: ((previous: Selected, next: Selected) => boolean) | undefined
) => Selected

Playground Link

Answer №2

The TypedUseSelectorHook remains a valuable tool and has not been officially deprecated. A mistake led to a pull request aiming to deprecate it, but this error was promptly corrected by the maintainers.

It is important to note that the createSelectorHook API mentioned as an alternative in another response is primarily designed for creating specialized useSelector hooks, rather than addressing broader use cases like the one presented here.

Therefore, continue utilizing the TypedUseSelectorHook instead of the createSelectorHook in this particular scenario.

To delve deeper into this topic, you can refer to this relevant GitHub issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What programming language is the best choice for Angular 2 development?

As someone who is new to Angular 2, I've discovered that developers have the option to use TypeScript, ES6, and ES5 for their development needs. I understand that TypeScript is considered the superset of ES6 and ES5. Given the stark differences in sy ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

Combine several .ts files into one bundle called package.js

Here is the structure of my code: Foo.ts: export module Foo { export function load() { } } Bar.ts: export module Bar { export function load() { } } webpack.config.js: const path = require('path'); module.exports = { entry: { ...

How can we transfer or exclude all boolean properties from one class to another or a "type"?

Within my Nestjs application, there is an entity class structured like this: @ObjectType() export class Companies { @Field(() => Int) @PrimaryGeneratedColumn({ type: 'int', name: 'id' }) public id: number; @Field() @Column ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

Using Typescript Type Guard will not modify the variable type if it is set in an indirect manner

TL;DR Differentiation between link1 (Operational) vs link2 (not functional) TypeGuard function validateAllProperties<T>(obj: any, props: (keyof T)[]): obj is T { return props.every((prop) => obj.hasOwnProperty(prop)) } Consider a variable ms ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Using TypeScript to transform a tuple type into an object

When dealing with a tuple type like: [session: SessionAgent, streamID: string, isScreenShare: boolean, connectionID: string, videoProducerOptions: ProducerOptions | null, connection: AbstractConnectionAgent, appData: string] there is a need to convert it ...

React Router Redux causing an infinite loop when navigating back

I recently encountered a strange issue with my React + Redux app. I am using React Router in combination with React Router Redux for routing, and I noticed some unexpected behavior. Clicking the back button once takes me from route 0 to -1 successfully. Ho ...

CDK Error: Unable to locate MethodResponse in AWS API Gateway configuration

I'm facing an issue in vscode while trying to access the MethodResponse interface from apigateway. Unfortunately, I'm getting an error message: The type 'typeof import(".../node_modules/aws-cdk-lib/aws-apigateway/index")' d ...

Setting cursor position in input field when navigating with arrow keys: What are the ways to achieve accessibility?

I have implemented arrow key navigation in a table, allowing navigation with the up, down, left, and right arrow keys. How can I ensure that the cursor always stays on the right side of the input field during navigation? Check out my Stackblitz example he ...

What are the reasons why Bootstrap icons are not functioning properly in ReactJS?

I am facing an issue with bootstrap icons not working in ReactJS. Click here to view my buttons This is the code for my post items: import React from 'react'; const PostListItem = () => { return ( <li className="app-list ...

Event for changing Ionic 2 page

Is there a way to execute code every time the page changes without adding an ngOnDestroy method to every page in Ionic 2? Instead of using Ionic 2 page lifecycle hooks like ionViewDidUnload, is there a simpler solution by adding a single method to the mai ...

The useNavigate function cannot be utilized in a custom hook created with createBrowserRouter

Presently, I've developed a custom hook specifically for handling login and logout functionalities export function useUser() { const { token, setToken, user, setUser } = useContext(AuthContext) const navigate = useNavigate() const { ...

External JavaScript files cannot be used with Angular 2

I am attempting to integrate the twitter-bootstrap-wizard JavaScript library into my Angular 2 project, but I keep encountering the following error: WEBPACK_MODULE_1_jquery(...).bootstrapWizard is not a function I have created a new Angular app using a ...

Verifying user privilege within settings database (written in Typescript for Aurelia framework)

Working on navigation with authorization. This is a snippet of my code: run(navigationInstruction: NavigationInstruction, next: Next) : Promise<any> { let requiredRoles = navigationInstruction.getAllInstructions() .map(i ...

Where can one find Typescript definitions when using typings?

Whenever I run typings install mongoose, it seems like the Typescript definitions are being fetched from https://github.com/louy/typed-mongoose This change feels a bit unexpected. Previously, they were sourced from DefinitelyTyped at https://github.com/ ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...