Typing State with useState
Desliza para mostrar el menú
React state stores data inside a component. In TypeScript, you define what type of data the state holds, so updates stay correct.
Basic Typing
const [count, setCount] = useState<number>(0);
countis anumber`;setCountaccepts only numbers.
With string:
const [name, setName] = useState<string>("Alex");
With array:
const [items, setItems] = useState<string[]>([]);
items is an array of strings.
With object:
const [user, setUser] = useState<{ name: string; age: number }>({
name: "Alex",
age: 25,
});
With null (common case):
type User = {
name: string;
age: number;
};
const [user, setUser] = useState<User | null>(null);
state can be User or null.
Type the state with <Type> so it always stores the correct data.
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 1. Capítulo 26
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Sección 1. Capítulo 26