How to correctly specify types for useState in React with TypeScript?
Hello colleagues! I started learning TypeScript in React and immediately encountered a problem with typing the useState hook.\n\nI have a simple component with a form where I need to store an object with name and age fields. Here's how I'm trying to do it:\n\n```typescript\nconst [user, setUser] = useState({ name: '', age: 0 });\n```\n\nIt seems to work, but when I want to pass this state to another component or function, TypeScript complains. Then I tried to explicitly specify the type:\n\n```typescript\ninterface User {\n name: string;\n age: number;\n}\n\nconst [user, setUser] = useState({ name: '', age: 0 });\n```\n\nNow it works, but I don't understand: do I always need to explicitly write the type? What if my state is an array? Or if the state can be null? I tried this:\n\n```typescript\nconst [items, setItems] = useState
No answers yet.
Log in to leave an answer
Blogs