React UseState Hook Types in TypeScript
This article will demonstrate the use of React hooks in TypeScriptuseState
.
React useState
hook definition
React useState
hooks play an important role when using functional components, from storing temporary data to receiving data from API calls. With the introduction of TypeScript, the developer experience has been improved in many ways.
TypeScript supports useState
adding types to React hooks. This is advantageous because TypeScript can infer types during setting values and even detect errors in types.
This can be mitigated earlier, allowing for safe deployment.
According to the TypeScript React documentation, TypeScript useState
has a common definition for React.
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
Here, S
is a generic type. It accepts the initial state, the hook can accept S
the state indicated by and a function Dispatch<SetStateAction<S>>
of type setState
.
An easy way to understand setState
the inferred type of a function is to hover over the variable in any appropriate IDE or text editor like VSCode.
useState
Using raw types with React Hooks
in TypeScript
useState
Hooks can set primitive types in application state. Primitive types include number
, , string
and boolean
.
This is an example of how to use useState
for primitive types in TypeScript.
const InfoComponent = () => {
const [name, setName] = React.useState<string>("");
const [age, setAge] = React.useState<number>(0);
const [isMarried, setIsMarried] = React.useState<boolean>(false);
React.useEffect(() => {
setName("Geralt");
setAge(95);
setIsMarried(false);
}, []);
return (
<>
<div>Witcher name : {name}</div>
<div>Age : {age}</div>
<div>Married : {isMarried ? 'Yes' : 'No'}</div>
</>
)
}
So useState
hooks have been used to store primitive types which are set useEffect
in the hook which is triggered once when the component mounts.
Using user-defined interfaces to store state in TypeScript
Even user-defined interfaces can be used useState
as types of hooks. The code snippet used in the previous section can be modified to store information in an interface, making the code more organized.
interface IUser {
name : string ;
age : number ;
isMarried : boolean ;
}
const InfoComponent = () => {
const [ state, setState ] = React.useState<IUser>({
name : "",
age : 0,
isMarried : false
});
React.useEffect(() => {
setState({
name : "Geralt",
age : 95,
isMarried : false
});
}, []);
return (
<>
<div>Witcher name : {state.name}</div>
<div>Age : {state.age}</div>
<div>Married : {state.isMarried ? 'Yes' : 'No'}</div>
</>
)
}
To setState
set optional fields in the function, as
the keyword can be used for type assertions. We have to setState
override the initial state using the optional state property passed to the function.
setState({
...state, ...{
name : "Geralt",
isMarried : "false"
} as unknown as IUser
});
So in the above example, age
the field is not set and the default value is used, which is state
provided by . State overwriting ...
is done with the or spread operator.
useState
Using Arrays in
TypeScript Hooks
When fetching data from an API, arrays can often be useState
used in the hook. The following code snippet demonstrates this while using useState
the hook to fetch data and display it.
interface IPost {
userId : number ;
id : number ;
title : string ;
body : string ;
}
export default App = () => {
const [ state, setState ] = React.useState<IPost[]>([]);
const getPosts = async () => {
const res : Response = await fetch("https://jsonplaceholder.typicode.com/posts");
const posts : IPost[] = await res.json();
setState(posts);
}
React.useEffect(() => {
getPosts();
}, []);
return (
<>
{
state.map( (post,index) => <div key={index}>
<h2>{post.title}</h2>
<div>{post.id}</div>
<p>{post.body}</p>
</div>
)
}
</>
)
}
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Handling exceptions with try..catch..finally in TypeScript
Publish Date:2025/04/15 Views:170 Category:TypeScript
-
This article will discuss try..catch..finally handling exceptions in TypeScript using the statement. Handling exceptions in TypeScript In TypeScript, try..catch..finally a block handles exceptions that occur during program runtime. It allow
Convert JSON object to a class in TypeScript
Publish Date:2025/04/15 Views:80 Category:TypeScript
-
Data on the internet flows in the form of strings, which can be converted into a very popular format called JSON. The JSON representation of this data usually represents an object or even a class in TypeScript. TypeScript provides the abili
Update TypeScript to the latest version using NPM
Publish Date:2025/04/15 Views:119 Category:TypeScript
-
This article provides a guide to update to the latest version of TypeScript using npm, which is the best and most popular method used by developers. This also gives us an in-depth look at what npm is and why to use it. Node Package Manager
Using jQuery and TypeScript
Publish Date:2025/04/15 Views:148 Category:TypeScript
-
This article provides the basic understanding and concepts of using jQuery with TypeScript. It guides on how to use jQuery in TypeScript through a coding example and outputs using various methods in TypeScript and provides knowledge about w
Checking for undefined in TypeScript
Publish Date:2025/04/15 Views:196 Category:TypeScript
-
This article will demonstrate how programmers can check for undefined in TypeScript using various coding examples and situations. It not only gives you an understanding of checking for undefined in TypeScript, but also helps in differentiat
exclude attribute in TypeScript
Publish Date:2025/04/15 Views:190 Category:TypeScript
-
This article will discuss excluding properties from a TypeScript type. The exclude property is used to create another type from an existing type with fewer or modified properties. Omit Exclude properties from types in TypeScript TypeScript
Function return types in TypeScript
Publish Date:2025/04/15 Views:174 Category:TypeScript
-
TypeScript is a strongly typed language and it is always encouraged to define the types correctly for all variables used in TypeScript. These types can help in development later, especially during debugging. In addition to variables, functi
Dictionary or map type in TypeScript
Publish Date:2025/04/15 Views:131 Category:TypeScript
-
Dictionaries or maps are used to quickly retrieve items from an object. TypeScript does not have any concept of maps or dictionaries. Plain JavaScript has objects that can set and retrieve key-value pairs. TypeScript provides Record types t
Regular expressions in TypeScript
Publish Date:2025/04/15 Views:104 Category:TypeScript
-
RegExp Is a regular expression used to match a fixed set of characters in a target string using TypeScript. RegExp Objects have many properties and methods. Each property has different options when pattern matching. Using regular expression