useState hook in Typescript functional component
Tags: webdev, javascript, programming, typescript
Published: 2022-12-08 14:52:09

React hooks are new features introduced in React Typescript. This article explains about useState hook in React Typescript.
useState hook used to store data in the typescript react component.

Typescript is a typed language, and every value must be declared with type.

So data stored in State must be declared with type explicitly.
Here is a syntax for useState hook

```
const [property, setProperty] = useState<type>(default value)
```
a default value can be passed

- numbers with zero
- String with ""
- boolean with false
- Array with []
- Objects with an empty object with property values have defaulted.

setProperty with type allows you to accept declared types and avoid runtime errors.

**React Typescript useState hook with primitive types**
Following are different primitive data types with the useState hook can also be defined with type inference

```
const [property, setProperty] = useState(default value)
```
type is inferred from the default value.
const [loading, isLoading] = useState(false)
Here, the loading value is inferred as a boolean type, isLoading function takes a boolean value

which is equivalent to

```
const [loading, isLoading] = useState<boolean>(false)
```
Here are String and number types

```
const [salary, setSalary] = useState<number>(5000)

const [name, setName] = useState<string>("john")
```
Here is an example to set the string in the useState **React hook example.**

```
import React, { Dispatch, FC, useState } from 'react';
interface Student {
    name: string ;
    marks: number ;
}
function UseStateExample(){
    const [message, setMessage] = useState("") // type is string

    const updateMessage=()=>{
        setMessage("w3schoolsio") 
    }
    return (
        <>
            <h1>Welcome - {message}</h1>
            <button onClick={() => { updateMessage() }}>Chnage</button>

        </>
    );
};

export default UseStateExample;
```
**React typescript useState object example**

This example talks about how to assign the object to State and assign default value using typescript.
Created an interface type for holding the object.
useState<Student> used with type, setting the state accepts object type only
Default value in the state is assigned with an empty object with default property values.

```
import React, {  useEffect, useState } from 'react';

interface Student {
    id: number;
    name: string;

  };

function UseStateExample(){
    const [student, setStudent] = useState<Student>({id:0,name:""});
useEffect(() => {
        setStudent({
            id:11,
            name : "john",
        });
    }, []);

    return (
        <>
            <h1>Welcome</h1>
          <div>
            id: {student.id} -  name: {student.name}
          </div>
          </>
    );
};

export default UseStateExample;
```
**React typescript useState Array of objects.**

This example assigns a setState hook with an array of objects

Declare an Object using an interface or Type alias interface example:

```
interface User {
    id: number;
    name: string;
  };
using type alias
type User = {
id: number;
name: string;
};
```
Initial value in useState in one of the following An initialized array of objects with square brackets[].
    const [users, setUsers] = useState<User[]>([]);
Another way, State accepts an array of generic types.

```
const [users, setUsers] = useState<{id: number; name: string}[]>([])
```
And the Type declared for the state is useState<User[]>
Here is an example

```
import React, {  useState } from 'react';

interface User {
    id: number;
    name: string;
  };

function UsersComponent(){
    const [users, setUsers] = useState<User[]>([]);

    const addUser=()=>{
        setUsers(prevUsers => [
          ...prevUsers,
          {id: 1, name: 'name'},
        ])
  }
    return (
        <>
            <h1>Welcome</h1>
            <button onClick={() => { addUser() }}>Add</button>
            <h1>Listof Users</h1>

            {users.map((user, index) => {
        return (
          <div key={index}>
            <div>
              id: {user.id} -  name: {user.name}
            </div>
          </div>
        );
      })}

        </>
    );
};

export default UsersComponent;

```