Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Typing Component State with useState | Typing React Components
Quizzes & Challenges
Quizzes
Challenges
/
TypeScript Essentials for React

bookTyping Component State with useState

When working with React, managing component state is a common task, and TypeScript helps you write safer code by ensuring your state values are always used as intended. The useState hook is the primary way to add state to functional components, but its type can change depending on what you store—primitives, objects, or arrays.

To type state managed by useState, you often do not need to declare the type explicitly; TypeScript will infer the type from the initial value. For example, if you write const [count, setCount] = useState(0), TypeScript knows count is a number. However, there are situations where you must provide the type explicitly, such as when the initial value does not convey enough information or is null.

Here are practical examples of how to type useState for different state shapes in your React components:

Typing state with primitives

If your state is a simple value like a number or string, TypeScript usually infers the type:

const [count, setCount] = useState(0); // count is inferred as number
const [title, setTitle] = useState("Hello"); // title is inferred as string

But if you want the state to start as null and later hold a value, you must specify the type:

const [username, setUsername] = useState<string | null>(null);

Typing state with objects

When your state is an object, TypeScript can infer the type if you provide the full initial value:

const [user, setUser] = useState({ name: "Alice", age: 30 }); // user is inferred as { name: string; age: number }

If the initial value is null or an empty object, you should declare the type:

type User = { name: string; age: number };
const [user, setUser] = useState<User | null>(null);

Typing state with arrays

For arrays, TypeScript infers the type from the initial value:

const [items, setItems] = useState<string[]>([]); // items is string[]

If you want to store objects in the array:

type Todo = { id: number; text: string; completed: boolean };
const [todos, setTodos] = useState<Todo[]>([]);

Tips for inferring vs. explicitly declaring state types

  • Prefer to let TypeScript infer the type when you initialize state with a value of the correct shape;
  • Explicitly declare the state type if the initial value is null, undefined, or does not provide enough information for inference;
  • Use union types (like string | null) when your state might be empty at first, then later hold a value;
  • For complex objects or arrays, consider defining and reusing a type or interface for clarity and maintainability.

1. When using useState, when should you explicitly declare the state type?

2. What is the benefit of typing state in React components?

question mark

When using useState, when should you explicitly declare the state type?

Select the correct answer

question mark

What is the benefit of typing state in React components?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 4.17

bookTyping Component State with useState

Deslize para mostrar o menu

When working with React, managing component state is a common task, and TypeScript helps you write safer code by ensuring your state values are always used as intended. The useState hook is the primary way to add state to functional components, but its type can change depending on what you store—primitives, objects, or arrays.

To type state managed by useState, you often do not need to declare the type explicitly; TypeScript will infer the type from the initial value. For example, if you write const [count, setCount] = useState(0), TypeScript knows count is a number. However, there are situations where you must provide the type explicitly, such as when the initial value does not convey enough information or is null.

Here are practical examples of how to type useState for different state shapes in your React components:

Typing state with primitives

If your state is a simple value like a number or string, TypeScript usually infers the type:

const [count, setCount] = useState(0); // count is inferred as number
const [title, setTitle] = useState("Hello"); // title is inferred as string

But if you want the state to start as null and later hold a value, you must specify the type:

const [username, setUsername] = useState<string | null>(null);

Typing state with objects

When your state is an object, TypeScript can infer the type if you provide the full initial value:

const [user, setUser] = useState({ name: "Alice", age: 30 }); // user is inferred as { name: string; age: number }

If the initial value is null or an empty object, you should declare the type:

type User = { name: string; age: number };
const [user, setUser] = useState<User | null>(null);

Typing state with arrays

For arrays, TypeScript infers the type from the initial value:

const [items, setItems] = useState<string[]>([]); // items is string[]

If you want to store objects in the array:

type Todo = { id: number; text: string; completed: boolean };
const [todos, setTodos] = useState<Todo[]>([]);

Tips for inferring vs. explicitly declaring state types

  • Prefer to let TypeScript infer the type when you initialize state with a value of the correct shape;
  • Explicitly declare the state type if the initial value is null, undefined, or does not provide enough information for inference;
  • Use union types (like string | null) when your state might be empty at first, then later hold a value;
  • For complex objects or arrays, consider defining and reusing a type or interface for clarity and maintainability.

1. When using useState, when should you explicitly declare the state type?

2. What is the benefit of typing state in React components?

question mark

When using useState, when should you explicitly declare the state type?

Select the correct answer

question mark

What is the benefit of typing state in React components?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3
some-alt