Table of Contents
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"23function 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 )12}1314export 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"23const ChildComp = ({4 setAutoPlay,5}: {6 setAutoPlay: React.Dispatch<React.SetStateAction<boolean>>7}) => {8 return <div>ChildComp</div>9}1011export default ChildComp
Types for other data types
We can declare the types for other data types as shown below:
1import React, { useState } from "react"23interface IPerson {4 name: string5 age: number6 hobbies: string[]7}89function App() {10 // boolean11 const [autoPlay, setAutoPlay] = useState<boolean>(false)12 // string13 const [name, setName] = useState<string>("Abhishek")14 // number15 const [age, setAge] = useState<number>(28)16 // array of string17 const [hobbies, setHobbies] = useState<string[]>([18 "coding",19 "trading",20 "reading",21 ])22 // object23 const [person, setPerson] = useState<IPerson>({24 name: "Abhishek",25 age: 28,26 hobbies: ["coding", "trading", "reading"],27 })28 return <div className="App"></div>29}3031export default App
Do follow me on twitter where I post developer insights more often!
Leave a Comment