Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Typing State with useState | Section
TypeScript for React Development

bookTyping State with useState

Scorri per mostrare il menu

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);
  • count is a number`;
  • setCount accepts 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.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 26

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 26
some-alt