MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Typing React Hooks, Generics, and Refs0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
9.1Typing Functional Components and Props in TypeScript9.2Typing React Hooks, Generics, and Refs9.3Typing Synthetic Events and Form Elements9.4Polymorphic Component Typing with As and ComponentPropsWithoutRef
HomeTutorialsReact.js for AdvancedTyping React Hooks, Generics, and Refs
Typing Synthetic Events and Form Elements

Typing React Hooks, Generics, and Refs

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While TypeScript's type inference handles simple hooks like useState(0) automatically, enterprise applications frequently require explicit generic typing for union states, null initializations, DOM references, and generic reusable custom hooks.


1. Typing useState

Inferred Primitives

1const [count, setCount] = useState(0); // Inferred as number
2const [text, setText] = useState(""); // Inferred as string

Explicit Generics for Complex Types and Nullable State

When a state object starts as null before network data loads, type inference as null will error when assigning an object later. Provide an explicit generic union:

1interface UserProfile {
2 id: string;
3 name: string;
4 email: string;
5}
6 
7// State can be UserProfile or null
8const [user, setUser] = useState<UserProfile | null>(null);
9 
10// Type unions for status flags
11type AuthStatus = "idle" | "authenticating" | "authenticated" | "error";
12const [status, setStatus] = useState<AuthStatus>("idle");

2. Typing useRef

useRef has two distinct use cases in TypeScript with very different type signatures:

Case A: DOM Element Reference (Read-Only Ref)

When referencing a physical DOM element, pass the HTML element type and initialize with null:

1import React, { useRef, useEffect } from "react";
2 
3export function AutoFocusSearchInput() {
4 // Read-only ref bound to an HTMLInputElement
5 const inputRef = useRef<HTMLInputElement>(null);
6 
7 useEffect(() => {
8 // Optional chaining required because inputRef.current might be null before mount
9 inputRef.current?.focus();
10 }, []);
11 
12 return (
13 <input
14 ref={inputRef}
15 type="text"
16 placeholder="Type here..."
17 className="px-4 py-2 bg-slate-800 text-white rounded border border-slate-700"
18 />
19 );
20}

Case B: Mutable Mutable Variable (Value Container)

When using useRef as an instance variable that persists across renders without triggering re-renders (like a timer ID or WebSocket handle), provide the type without null initialization if not needed:

1// Mutable ref container holding a timer ID
2const timerRef = useRef<number | undefined>(undefined);
3 
4const startTimer = () => {
5 timerRef.current = window.setInterval(() => {
6 console.log("Tick");
7 }, 1000);
8};
9 
10const stopTimer = () => {
11 if (timerRef.current !== undefined) {
12 clearInterval(timerRef.current);
13 }
14};

3. Typing useReducer

Discriminated unions provide complete type safety for reducer actions:

1interface State {
2 count: number;
3 error: string | null;
4}
5 
6type Action =
7 | { type: "INCREMENT"; payload: number }
8 | { type: "DECREMENT"; payload: number }
9 | { type: "RESET" }
10 | { type: "SET_ERROR"; payload: string };
11 
12function counterReducer(state: State, action: Action): State {
13 switch (action.type) {
14 case "INCREMENT":
15 return { ...state, count: state.count + action.payload, error: null };
16 case "DECREMENT":
17 return { ...state, count: state.count - action.payload, error: null };
18 case "RESET":
19 return { count: 0, error: null };
20 case "SET_ERROR":
21 return { ...state, error: action.payload };
22 default: {
23 const _exhaustive: never = action;
24 return state;
25 }
26 }
27}

4. Generic Custom Hooks

Generic custom hooks allow components to consume typed utilities dynamically:

1import { useState, useEffect } from "react";
2 
3interface FetchState<T> {
4 data: T | null;
5 isLoading: boolean;
6 error: Error | null;
7}
8 
9export function useFetchData<T>(url: string): FetchState<T> {
10 const [state, setState] = useState<FetchState<T>>({
11 data: null,
12 isLoading: true,
13 error: null,
14 });
15 
16 useEffect(() => {
17 let isMounted = true;
18 
19 fetch(url)
20 .then((res) => res.json())
21 .then((data: T) => {
22 if (isMounted) setState({ data, isLoading: false, error: null });
23 })
24 .catch((error: Error) => {
25 if (isMounted) setState({ data: null, isLoading: false, error });
26 });
27 
28 return () => {
29 isMounted = false;
30 };
31 }, [url]);
32 
33 return state;
34}
35 
36// Consumption with full type inference:
37interface Order {
38 id: string;
39 total: number;
40}
41 
42// data is strictly typed as Order[] | null
43// const { data, isLoading } = useFetchData<Order[]>("/api/orders");

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What happens if you initialize useState with null without a generic type parameter: const [user, setUser] = useState(null)?
Question 2
How should you type a ref intended to attach to an HTML <canvas> element?
Question 3
In a typed reducer, what is the benefit of the const _exhaustive: never = action statement in the default case?
Question 4
Why must inputRef.current be checked with optional chaining (inputRef.current?.focus()) before calling methods?
Question 5
How do generics benefit custom hooks like useFetchData<T>(url)?
Next Lesson

Typing Synthetic Events and Form Elements

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Typing Functional Components and Props in TypeScriptTyping Synthetic Events and Form Elements

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext