सामग्री पर जाएँ

लेसन 94 · TypeScript with React

State, Refs, Context और Reducers को Type देना

React hooks को सही type दें: union और null के साथ useState, DOM और मानों के लिए useRef, createContext, discriminated-union reducers और custom hook types।

props React प्रोग्राम का सिर्फ़ आधा हिस्सा हैं। दूसरा आधा वह है जो कंपोनेंट के अंदर रहता है: state, refs, context, reducers और आपके अपने hooks। TypeScript का सबसे ज़्यादा फ़ायदा यहीं मिलता है, क्योंकि state समय के साथ बदलता है और वहाँ की गलतियाँ (ऑब्जेक्ट (object) की उम्मीद में null मिला मान, वह action जिसे कोई नहीं संभालता) आँख से पकड़ना सबसे मुश्किल है।

ज़्यादातर hook types आपके पास किए आर्ग्युमेंट (argument) से infer होते हैं। हुनर उन गिनी-चुनी जगहों को जानने में है जहाँ inference काफ़ी नहीं और आपको मदद करनी पड़ती है: ख़ाली ऐरे, null से शुरू होने वाला मान, बिना समझदार डिफ़ॉल्ट वाला context, action union। यह लेसन एक-एक करके हर hook से गुज़रता है। यह TypeScript and React पर आगे बढ़ता है और Generic Components and Advanced Types की तैयारी करता है।

इस साइट का एडिटर सिर्फ़ JavaScript चलाता है, इसलिए यहाँ का हर TypeScript ब्लॉक सिर्फ़ पढ़ने के लिए है (tsx)। लाइव उदाहरण JavaScript समकक्ष चलाते हैं ताकि आप वह व्यवहार देखें जिसका types वर्णन करते हैं: वे असंभव states जिन्हें वे मना करते हैं, वह null जिसकी चेतावनी देते हैं, और वह गलती जिसे वे compile error बना देते हैं।

useState

जब शुरुआती मान type दिखा दे, तो आप कुछ नहीं लिखते:

TSX
const [count, setCount] = useState(0);        // number
const [name, setName] = useState('');          // string
const [done, setDone] = useState(false);       // boolean

TypeScript 0 से number infer करता है, और अब setCount('five') एरर है। तीन स्थितियों में आपको type आर्ग्युमेंट जोड़ना होता है।

1. state ख़ाली या null से शुरू होता है। अकेला [] never[] (ऐसा ऐरे जिसमें कुछ काम का नहीं रह सकता) infer होगा, और अकेला null सिर्फ़ null।

TSX
type User = { id: number; name: string };

const [items, setItems] = useState<string[]>([]);
const [user, setUser] = useState<User | null>(null);

User | null के साथ compiler आपको डेटा छूने से पहले ग़ायब वाले मामले से निपटने को मजबूर करता है:

TSX
return <p>{user.name}</p>;            // error TS18047: 'user' is possibly 'null'.
return <p>{user ? user.name : 'Guest'}</p>;   // ठीक है
return <p>{user?.name ?? 'Guest'}</p>;        // यह भी ठीक है

2. state स्ट्रिंग (string) literals का union है। बिना मदद के TypeScript 'idle' को string तक चौड़ा कर देता है:

TSX
type Status = 'idle' | 'loading' | 'done';
const [status, setStatus] = useState<Status>('idle');
setStatus('finished');   // error TS2345: Argument of type '"finished"' is not assignable to parameter of type 'SetStateAction<Status>'.

3. शुरुआती मान lazily निकाला जाता है और चौड़ा type लौटाता है: useState<Settings>(() => readSettings())।

setter का type आपके लिए तय होता है। वह नया मान या updater फ़ंक्शन (function) लेता है, setCount((previous) => previous + 1), जहाँ previous का type state वाला है। जब नया मान पुराने पर निर्भर हो तो updater को प्राथमिकता दें।

असंभव states को असंभव बनाएँ

बहुत आम डिज़ाइन कई बूलियन (boolean) हैं: isLoading, isError, और data। चार बूलियन सोलह combinations की अनुमति देते हैं, और ज़्यादातर बेमानी होते हैं ("loading और फ़ेल एक साथ")। states का union सिर्फ़ सार्थक वाले होने देता है, और TypeScript हर state को ठीक वही डेटा रखने पर मजबूर करता है जो उसका है।

TSX
type FetchState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; users: User[] }
  | { status: 'error'; message: string };

const [state, setState] = useState<FetchState>({ status: 'idle' });

if (state.status === 'success') {
  // यहाँ TypeScript जानता है कि state.users मौजूद है
  return <p>{state.users.length} users</p>;
}
if (state.status === 'error') {
  return <p role="alert">{state.message}</p>;
}

हर if के अंदर compiler union को narrow करता है, इसलिए state.users सिर्फ़ success में उपलब्ध है, और कहीं और state.message पढ़ना एरर है। दोनों डिज़ाइन साथ-साथ आज़माएँ। दोनों में "Start" और फिर "Fail" दबाएँ:

बूलियन flags बनाम state union

"Start" फिर "Fail" के बाद बूलियन वर्शन isLoading = true, isError = true और लाल चेतावनी दिखाता है, क्योंकि एक flag सेट करने से दूसरा साफ़ नहीं होता। union वर्शन {"status":"error","message":"Network down"} दिखाता है: नया state सेट करने से पुराना बदल जाता है, इसलिए "loading" अपने-आप ग़ायब हो जाता है। TypeScript में union वर्शन इस विरोधाभास को लिख भी नहीं सकता। state के लिए यह सबसे काम की मॉडलिंग तरकीब है; Choosing State Structure देखें।

useRef

useRef के दो काम हैं, और उनका typing थोड़ा अलग है।

DOM एलिमेंट का reference। एलिमेंट type दें और null से शुरू करें, क्योंकि React पहले रेंडर के बाद ref भरता है:

TSX
import { useEffect, useRef } from 'react';

function SearchField() {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();      // current HTMLInputElement | null है
  }, []);

  return <input ref={inputRef} />;
}

inputRef.current का type HTMLInputElement | null है, जो पहले रेंडर को ईमानदारी से दिखाता है: अभी कुछ जुड़ा नहीं। ?. इसे संभालता है। inputRef.current! से इसे चुप न करें, जब तक आप ऐसे कोड में न हों जो सिर्फ़ mount के बाद चलता है (इवेंट handler या इफ़ेक्ट) और आपने इस पर सोचा हो। एलिमेंट type का नाम मायने रखता है: HTMLInputElement, HTMLButtonElement, HTMLDivElement, HTMLFormElement, HTMLCanvasElement, इत्यादि।

रेंडर शुरू न करने वाला बदलने योग्य डिब्बा। यहाँ ref आपका चुना मान रखता है, जैसे timer id या पिछला मान:

TSX
const timerId = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const clicks = useRef(0);        // { current: number } infer हुआ

function schedule() {
  clearTimeout(timerId.current);
  timerId.current = setTimeout(() => console.log('fired'), 300);
}

React 19 के types में useRef को हमेशा शुरुआती आर्ग्युमेंट चाहिए (इसीलिए ऊपर undefined)। देखें कि typing व्यवहार में null के बारे में क्या कहती है:

React के भरने तक ref null रहता है

पहली लॉग पंक्ति render 1: inputRef.current is null है: पहले रेंडर के दौरान इनपुट अभी मौजूद नहीं। फिर इफ़ेक्ट चलता है और effect: inputRef.current is INPUT प्रिंट करता है। "Count a click" दो बार दबाएँ और लॉग clicks.current = 1 और clicks.current = 2 पढ़ता है, पर पैराग्राफ़ अब भी 0 कहता है, क्योंकि ref बदलने से री-रेंडर नहीं होता। "Re-render" दबाएँ और वह 2 हो जाता है। ठीक इसीलिए DOM ref का type | null है और value ref का नहीं। और useRef में।

React 19 में ref साधारण prop है, इसलिए अपना इनपुट उपलब्ध कराने वाला कंपोनेंट बस उसे declare करता है:

TSX
import type { Ref } from 'react';

type TextFieldProps = { label: string; ref?: Ref<HTMLInputElement> };

function TextField({ label, ref }: TextFieldProps) {
  return (
    <label>
      {label} <input ref={ref} />
    </label>
  );
}

forwardRef की ज़रूरत नहीं। parent useRef<HTMLInputElement>(null) के साथ ref={inputRef} पास करता है।

useEffect, useMemo और useCallback

ये ज़्यादातर अपने types infer करते हैं। दो नियम मायने रखते हैं:

  • इफ़ेक्ट callback को कुछ नहीं या cleanup फ़ंक्शन लौटाना चाहिए। async फ़ंक्शन promise लौटाता है, इसलिए यह एरर है: useEffect(async () => { ... }, []) Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'. देता है। अंदर async फ़ंक्शन परिभाषित करके बुलाएँ, जैसा Data Fetching में है।
  • useMemo और useCallback अपना type आपके लौटाए से लेते हैं; callbacks के parameters annotate करें क्योंकि और कोई चीज़ TypeScript को नहीं बताती कि वे क्या हैं: useCallback((id: number) => remove(id), [remove])।

Context

createContext को डिफ़ॉल्ट मान चाहिए, और डिफ़ॉल्ट type तय करता है। दो तरीक़े हैं।

1. असली डिफ़ॉल्ट। तब अच्छा है जब context optional हो और उसका समझदार fallback हो:

TSX
type Theme = 'light' | 'dark';
const ThemeContext = createContext<Theme>('light');

2. null और एक guard hook। तब अच्छा है जब provider ज़रूरी हो, जो हर stateful चीज़ का आम मामला है। context type में null शामिल है, और एक custom hook उसे एक बार जाँचता है ताकि consumers कभी null न देखें:

TSX
import { createContext, useContext, useState } from 'react';
import type { ReactNode } from 'react';

type Theme = 'light' | 'dark';

type ThemeContextValue = {
  theme: Theme;
  toggleTheme: () => void;
};

const ThemeContext = createContext<ThemeContextValue | null>(null);

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light');
  const value: ThemeContextValue = {
    theme,
    toggleTheme: () => setTheme((current) => (current === 'light' ? 'dark' : 'light')),
  };
  return <ThemeContext value={value}>{children}</ThemeContext>;
}

export function useTheme(): ThemeContextValue {
  const context = useContext(ThemeContext);
  if (context === null) {
    throw new Error('useTheme must be used inside <ThemeProvider>');
  }
  return context;
}

if के बाद TypeScript ने context को ThemeContextValue | null से ThemeContextValue तक narrow कर दिया है, इसलिए बुलाने वाले बिना null जाँच के const { theme, toggleTheme } = useTheme(); लिखते हैं। context ऑब्जेक्ट को export न करें, सिर्फ़ provider और hook export करें; तब context को गलत इस्तेमाल करना असंभव है। React 19 में आप .Provider के बिना सीधे <ThemeContext value={...}> रेंडर कर सकते हैं। रन टाइम वर्शन:

guard hook वाला context

अब वह गलती जिसके लिए guard है: provider के बाहर hook इस्तेमाल करना। null डिफ़ॉल्ट और बिना guard के विफलता कहीं दूर उलझाने वाला Cannot destructure property 'theme' of ... as it is null होती। guard के साथ संदेश असली समस्या का नाम लेता है। और पैटर्न Context और Context Patterns में।

provider के बिना hook इस्तेमाल करना (जानबूझकर फ़ेल)

पेज ख़ाली रहता है, और कंसोल Error: useTheme must be used inside <ThemeProvider> दिखाता है। एक पंक्ति के guard ने रहस्य को साफ़ निर्देश बना दिया।

Reducers और discriminated-union actions

reducer एक फ़ंक्शन (state, action) => newState है। TypeScript यहाँ चमकता है क्योंकि action एक discriminated union है: हर action में type फ़ील्ड (discriminant) है, और बाकी फ़ील्ड उस पर निर्भर हैं।

TSX
import { useReducer } from 'react';

type CartState = {
  lines: Record<number, number>;   // product id -> मात्रा
};

type CartAction =
  | { type: 'added'; id: number }
  | { type: 'removed'; id: number }
  | { type: 'quantitySet'; id: number; quantity: number }
  | { type: 'cleared' };

function cartReducer(state: CartState, action: CartAction): CartState {
  switch (action.type) {
    case 'added':
      return { lines: { ...state.lines, [action.id]: (state.lines[action.id] ?? 0) + 1 } };
    case 'removed': {
      const { [action.id]: _removed, ...rest } = state.lines;
      return { lines: rest };
    }
    case 'quantitySet':
      return { lines: { ...state.lines, [action.id]: action.quantity } };
    case 'cleared':
      return { lines: {} };
    default: {
      const unreachable: never = action;
      throw new Error('Unhandled action: ' + JSON.stringify(unreachable));
    }
  }
}

function Cart() {
  const [state, dispatch] = useReducer(cartReducer, { lines: {} });
  dispatch({ type: 'added', id: 7 });           // ठीक है
  dispatch({ type: 'quantitySet', id: 7 });     // error: Property 'quantity' is missing
  dispatch({ type: 'add', id: 7 });             // error: '"add"' is not assignable to the action types
  return null;
}

तीन बातें ध्यान दें:

  1. switch में narrowing। case 'quantitySet' में action.quantity है; case 'cleared' में कोई और फ़ील्ड नहीं। type की टाइपो एरर हैं।
  2. dispatch का type आपके लिए reducer से तय होता है। उसका type Dispatch<CartAction> है; dispatch को prop की तरह पास करते समय यह नाम इस्तेमाल करें।
  3. never की तरकीब। default में हर case संभाला जा चुका है, इसलिए action का type never है। उसे never वेरिएबल (variable) को assign करना तभी compile होता है जब यह सच हो। अगर कोई union में { type: 'discounted'; code: string } जोड़े और case भूल जाए, तो assignment एरर बन जाता है, जो ठीक उस reducer की ओर इशारा करता है जिसे अपडेट करना है।

याद रखें कि types रन टाइम पर ग़ायब हो जाते हैं, इसलिए default शाखा को फिर भी throw करना चाहिए: यह आपको ऐसे action से बचाती है जिसके बारे में आप नहीं जानते थे, जैसे बिना type वाले कोड से आया। रन टाइम की तस्वीर यह है:

exhaustive default वाला reducer

कंसोल बिना किसी कंपोनेंट के reducer को काम करते दिखाता है: added 7 -> {"lines":{"7":1}}, added 7 -> {"lines":{"7":2}}, और इसी तरह, आख़िर में caught: Unhandled action: {"type":"add","id":7}। वह 'add' वही टाइपो है जिसे TypeScript कॉल की जगह पर चिह्नित करता। लाइव widget में बटन ऑब्जेक्ट {"7":1,"9":1} जैसे बनाते हैं। और Reducers में।

custom hook के return types

custom hook एक फ़ंक्शन है, और आप उसके parameters और रिटर्न वैल्यू (return value) को किसी भी दूसरे की तरह type देते हैं। दो आकार आम हैं:

TSX
import { useCallback, useState } from 'react';

// useState जैसा tuple: बुलाने वाला हिस्सों को नाम देता है।
function useToggle(initial = false): [boolean, () => void] {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn((current) => !current), []);
  return [on, toggle];
}

// ऑब्जेक्ट, जब दो से ज़्यादा चीज़ें हों या नाम मायने रखें।
function useCounter(start = 0) {
  const [count, setCount] = useState(start);
  return {
    count,
    increment: () => setCount((c) => c + 1),
    reset: () => setCount(start),
  };
}

tuple के लिए return type लिखें ([boolean, () => void]) या return [on, toggle] as const से ख़त्म करें। इसके बिना TypeScript (boolean | (() => void))[] infer करता है, ऐसा ऐरे जो दोनों में से कोई भी रख सकता है, और destructuring से दोनों नामों को बेकार union मिलता है। ऑब्जेक्ट के लिए return type infer होता है और compiler नाम और types की गारंटी देता है। अच्छा नियम: ठीक दो मान हों जहाँ कॉल की जगह पर नाम बदलना स्वाभाविक हो तो tuple (ट्यूपल), वरना ऑब्जेक्ट।

Tuple hook और object hook

वही hook अलग नामों से दो बार इस्तेमाल हुआ है (isOpen/toggleOpen और isDark/toggleDark); यही tuple का फ़ायदा है। counter hook ऑब्जेक्ट लौटाता है, इसलिए बुलाने वाला सिर्फ़ अपनी ज़रूरत का लेता है। hook डिज़ाइन Custom Hooks में है।

एक छोटी checklist

  • inference को काम करने दें; null, ख़ाली ऐरे और literal unions के लिए useState<T> जोड़ें।
  • बूलियन की जगह states के union से state का मॉडल बनाएँ।
  • DOM nodes के लिए useRef<HTMLElement>(null) (मान | null है); मानों के लिए useRef<T>(initial)।
  • context: type में | null रखें और throw करने वाला hook दें, ताकि consumers को साफ़ type मिले।
  • reducer actions discriminated union हों; switch के अंत में never जाँच रखें।
  • दो मान लौटाने वाले hooks tuple (साफ़ type के साथ) लौटा सकते हैं; वरना ऑब्जेक्ट लौटाएँ।
  • शॉर्टकट के तौर पर any और as से बचें; ज़रूरत हो तो कारण कमेंट (comment) में लिखें।

अपनी समझ जाँचें

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. TypeScript में useState([]) परेशानी क्यों करता है, और इलाज क्या है?

    ख़ाली array literal TypeScript को एलिमेंट type की कोई जानकारी नहीं देता। useState<string[]>([]) जैसा type आर्ग्युमेंट दें।
  2. 2. बूलियन-flags डेमो में Start फिर Fail दबाने के बाद क्या हुआ?

    हर setter सिर्फ़ अपना flag बदलता है। states का union पूरा state बदल देता है, इसलिए विरोधाभास नहीं हो सकते।
  3. 3. useRef<HTMLInputElement>(null).current का type HTMLInputElement | null क्यों है?

    डेमो ने पहले रेंडर के दौरान null और इफ़ेक्ट में INPUT लॉग किया। type वही ईमानदार समय-रेखा दिखाता है।
  4. 4. reducer की default शाखा में never assignment का मक़सद क्या है?

    सारे cases संभाले हों तो action का type never होता है। कोई case छूटे तो assignment compile नहीं होता, जो reducer की ओर इशारा करता है।
  5. 5. एक hook बिना किसी annotation के [on, toggle] लौटाता है। TypeScript क्या infer करता है, और आप इसे कैसे ठीक करेंगे?

    array literals tuple नहीं, ऐरे के रूप में infer होते हैं। return type annotate करें या as const इस्तेमाल करें ताकि हर स्थिति अपना type रखे।

सारांश

  • useState अपना type infer करता है; null, ख़ाली ऐरे और literal unions के लिए type आर्ग्युमेंट जोड़ें, और कई बूलियन की जगह states का union इस्तेमाल करें।
  • DOM refs | null मान वाले useRef<Element>(null) हैं; value refs कुछ भी रखते हैं और री-रेंडर नहीं करते।
  • इफ़ेक्ट callbacks async नहीं हो सकते; callback parameters को types दें।
  • ज़रूरी providers के लिए context Value | null से बनाएँ और throw करने वाला hook दें, ताकि consumers को non-null type और साफ़ एरर मिले।
  • reducer actions को discriminated union की तरह type दें और never जाँच से ख़त्म करें; dispatch का type अपने-आप बनता है।
  • custom hooks से tuples (साफ़ type या as const के साथ) या ऑब्जेक्ट लौटाएँ।

अगला: Generic Components and Advanced Types

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।