The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

How to set a TypeScript type to an useState hook

posted on 23.1.2023 by Below Surface in "TypeScript"

Let's say we have a React application with TypeScript. When using the useState hook, it can be confusing where to add the type declaration. In our example, the held data will be an array of users. So firstly, we will create a typing for a single user like this:

export type User = {
    _id: string;
    userName: string;
    userRole: string;
    password: string;

Our useState hook for holding the user's array currently looks like this:

const [allUsers, setAllUsers] = useState([]);

To tell TypeScript, that "allUsers" will hold an array of users, just change your code to be the following:

const [allUsers, setAllUsers] = useState<User[]>([]);


usestate hook
type declaration

More posts of this category

Find out the HTML input change event type in VS Code

An easy way to find out the correct input change event type for TypeScript


How to instanciate a file object in TypeScript

Use the React useState hook to hold a file data object and properly instanciate it