← Back to TypeScript Course | Chapter 14: TypeScript with React | Lesson 7 of 8

Context API की Typing

Context API components को हर level में props pass किए बिना values share करने देती है। TypeScript context value को describe कर सकता है ताकि consumers और providers एक जैसा contract उपयोग करें।
Syntax
typescript
const Context = createContext<ContextType | undefined>(undefined);
const value = useContext(Context);

एक Typed Context बनाना

एक typed context बनाने का मतलब है createContext के generic argument के रूप में एक interface pass करना, इसलिए उस context का हर consumer हर उपयोग पर type फिर से declare किए बिना अपने आप सही shape पाता है।

उदाहरण: Creating a Typed Context

typescript
import React, { createContext } from "react";

interface ThemeContextValue {
	theme: "light" | "dark";
}

const ThemeContext = createContext<ThemeContextValue>({ theme: "light" });

export default ThemeContext;

useContext उपयोग करना

useContext जो भी type context बनाया गया था वह return करता है, इसलिए एक बार context खुद correctly typed हो जाए, इसे tree में कहीं भी उपयोग करने के लिए call site पर कोई extra type annotations नहीं चाहिए।

उदाहरण: Using useContext

typescript
import React, { createContext, useContext } from "react";

const ThemeContext = createContext({ theme: "light" });

function ThemedText(): React.JSX.Element {
	const { theme } = useContext(ThemeContext);
	return <p>Theme: {theme}</p>;
}

export default ThemedText;

State के साथ Context

Context को state के साथ combine करने का मतलब है context की value को current state और इसके setter function दोनों रखने वाले एक object के रूप में type करना, consumers को पूरी type safety के साथ shared state पढ़ने और update करने दोनों की अनुमति देते हुए।

उदाहरण: Context with State

typescript
import React, { createContext, useState } from "react";

interface CountContextValue {
	count: number;
	setCount: (n: number) => void;
}

const CountContext = createContext<CountContextValue | undefined>(undefined);

export default CountContext;

एक Safe Context Hook बनाना

एक safe context hook useContext को एक custom hook में wrap करता है जो throw करता है अगर context को इसके provider के बाहर access किया जाए, एक possibly-undefined context value को consumers के लिए एक guaranteed non-null type में बदलते हुए।

उदाहरण: Creating a Safe Context Hook

typescript
import React, { createContext, useContext } from "react";

const CountContext = createContext<{ count: number } | undefined>(undefined);

function useCount() {
	const ctx = useContext(CountContext);
	if (!ctx) throw new Error("useCount must be used within CountContext.Provider");
	return ctx;
}

export default useCount;

Complex Values वाला Context

Complex, deeply nested values रखने वाले context को value के interface को छोटे named types में तोड़ने से फ़ायदा मिलता है, context के overall type को एक बड़े inline object type के बजाय readable रखते हुए।

उदाहरण: Context with Complex Values

typescript
import React, { createContext } from "react";

interface User {
	name: string;
}
interface AppContextValue {
	user: User | null;
	permissions: string[];
}

const AppContext = createContext<AppContextValue>({ user: null, permissions: [] });

export default AppContext;
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. useContext को इसके Provider के बाहर call करना और बिना notice किए default value या undefined पाना।
  2. एक untyped default pass करना जैसे createContext({}), इसलिए consumers value का type खो देते हैं।
  3. Context को T | undefined typed करना और फिर इसे check के बिना उपयोग करना, जो error देता है।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.