Use TypeScript with React-Hooks

Tram Ho

In this article I will share how to use types and hooks in react-typescript app build

I. Use type with useState

useState is definitely a daily hook for each react dev , useState allows us to initialize and manage state inside function component similar to this.state in class component , following is a simple example using useState to declare a state with typescript

To specify a type for the state generated by useState , we specify the type with the syntax useState <type> (defaultValue) . Note that it is possible to specify a mixed type for state : useState <string | null> (null) .

II. Use type with useRef

Similar to createRef in classe component , useRef is a hook that creates an object that allows binding to DOM element inside function component . Specifying the type for the ref object using useRef is quite similar to the useState above, as can be seen from the following example:

III. Use type with useContext

useContext allows you to manipulate Context API more easily, if you have not learned about Context API , simply understand it is a React api that allows us to create states accessible by low components. without the effort of passing props and multiple levels of components , please refer here .
With typescript , we need to specify the type from the step that created the context

Then specify the type in the step to access the data

By the way above, we were able to handle the type for the state generated by the Context API .

III. Use type with useReducer

useReducer is an alternative to useState when we need to manage complex states , which is quite similar to state management with the redux library, perhaps hence the name reducer .
In order to use useReducer with typescript properly, we should note that specifying the type for action and state will be slightly different, assuming we have a simple state , but a count value and two actions allow us to. increase or decrease the count value, and do the following.

We use interfaces to declare types for state, actions and use the Typescript enumapi that allows us to define a group of variable names that do not change, used to define the type cases that will have actions . After setup is complete, we just need to declare reducer :

Then use the newly created reducer inside the component :

Above I have just shared how to use typescript with some React Hooks , the article is referenced from the article The React TypeScript Cheatsheet – How To Set Up Types on Hooks , hope the information in this article will be useful. .

Share the news now

Source : Viblo