Skip to content

How to add type to useState while using TypeScript with React

Jul 30, 2022Abhishek EH2 Min Read
How to add type to useState while using TypeScript with React

Have you started using TypeScript with React recently and are confused about how to declare types for your state in the useState hook? In this article, we will see the type declarations for boolean, string, number, array, and object.

Type definition for boolean values

If you need to declare a state to store a boolean value, then you can declare it as shown below:

1const [autoPlay, setAutoPlay] = useState<boolean>(false)

The type needs to be passed after the useState, inside angular brackets.

You can use it in your application as follows:

1import React, { useState } from "react"
3function App() {
4 const [autoPlay, setAutoPlay] = useState<boolean>(false)
5 return (
6 <div className="App">
7 <button onClick={() => setAutoPlay(existingValue => !existingValue)}>
8 Turn autoplay {autoPlay ? "on" : "off"}
9 </button>
10 </div>
11 )
14export default App

It is not mandatory to specify the type as TypeScript can infer the type from the type of the initial value.

If we try to set a different type value, say a string using setAutoPlay("true") then we will get the following error:

1Argument of type '""' is not assignable to parameter of type 'SetStateAction<boolean>'.ts(2345)

Type definition for setState function

If you need to pass the setState function as a prop to a child component, then you can specify the type of the useState function as follows:

1import React from "react"
3const ChildComp = ({
4 setAutoPlay,
5}: {
6 setAutoPlay: React.Dispatch<React.SetStateAction<boolean>>
7}) => {
8 return <div>ChildComp</div>
11export default ChildComp

Types for other data types

We can declare the types for other data types as shown below:

1import React, { useState } from "react"
3interface IPerson {
4 name: string
5 age: number
6 hobbies: string[]
9function App() {
10 // boolean
11 const [autoPlay, setAutoPlay] = useState<boolean>(false)
12 // string
13 const [name, setName] = useState<string>("Abhishek")
14 // number
15 const [age, setAge] = useState<number>(28)
16 // array of string
17 const [hobbies, setHobbies] = useState<string[]>([
18 "coding",
19 "trading",
20 "reading",
21 ])
22 // object
23 const [person, setPerson] = useState<IPerson>({
24 name: "Abhishek",
25 age: 28,
26 hobbies: ["coding", "trading", "reading"],
27 })
28 return <div className="App"></div>
31export default App

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com