How to Add a Type to useState Hook in TypeScript
How can we add a type to a useState()
hook in TypeScript?
Suppose we have an interface User
.
interface User {
id: number,
};
We want to create a state using useState()
and apply this interface to the state.
import React, { useState } from "react";
const [user, setUser] = useState<User>({id: 1});
Check out the type in the
DefinitelyTyped
source.