State की Typing
In this page:
const [state, setState] = useState<StateType>(initialValue);
Basic useState Typing
Basic useState typing आपके pass किए initial value से अपने आप infer होती है, इसलिए useState(0) किसी manual annotation की ज़रूरत के बिना already आपको number typed एक state variable देता है।
उदाहरण: Basic useState Typing
import React, { useState } from "react";
function Counter(): React.JSX.Element {
const [count, setCount] = useState(0);
return <p>{count}</p>;
}
export default Counter;
Explicit State Types
useState<T>() को एक explicit type argument चाहिए जब initial value उस type को पूरी तरह describe न करे जो आप असल में चाहते हैं — उदाहरण के लिए जब state बाद में कई अलग shapes में से एक रख सकता है।
उदाहरण: Explicit State Types
import React, { useState } from "react";
type Status = "idle" | "loading" | "done";
function Loader(): React.JSX.Element {
const [status, setStatus] = useState<Status>("idle");
return <p>{status}</p>;
}
export default Loader;
Nullable State
Nullable state को explicitly useState<User | null>(null) के रूप में typed किया जाता है, जो expected object पर एक property access करने से पहले state पढ़ने वाली हर जगह को इसे null नहीं है पहले check करने पर मजबूर करता है।
उदाहरण: Nullable State
import React, { useState } from "react";
interface User {
name: string;
}
function Profile(): React.JSX.Element {
const [user, setUser] = useState<User | null>(null);
return <p>{user ? user.name : "No user"}</p>;
}
export default Profile;
Array State
Array state को useState<Item[]>([]) जैसे एक explicit type argument का फ़ायदा मिलता है, क्योंकि एक empty array अकेले TypeScript को कोई जानकारी नहीं देता कि array किस तरह के items eventually रखने वाला है।
उदाहरण: Array State
import React, { useState } from "react";
interface Item {
id: number;
label: string;
}
function List(): React.JSX.Element {
const [items, setItems] = useState<Item[]>([]);
return <p>{items.length} items</p>;
}
export default List;
Functional Updates के साथ State
Functional updates — setState(prev => ...) — prev parameter को state के current type के रूप में अपने आप type करते हैं, आपको type को हाथ से फिर से declare किए बिना previous value से safely एक नई value compute करने देते हुए।
उदाहरण: State with Functional Updates
import React, { useState } from "react";
function Counter(): React.JSX.Element {
const [count, setCount] = useState(0);
const increment = () => setCount((prev) => prev + 1);
return <button onClick={increment}>{count}</button>;
}
export default Counter;
useState([])लिखना औरnever[]मिलना, इसलिए एक item push करना error देता है;useState<Item[]>([])उपयोग करें।useState(null)से शुरू करना और बाद में एक user object set करना, जब state typenullinfer होता है औरuseState<User | null>(null)चाहता है।- State को directly mutate करना, जैसे
items.push(x),setItems([...items, x])call करने के बजाय।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: