TypeScript Course
TypeScript
/
Intermediate

React: Typing Hooks (Context, Refs, Memo)

Definition

Applying TypeScript to advanced React Hooks, specifically `useContext`, `useRef`, `useMemo`, and `useCallback`.

Explain Like I'm New

Hooks are just functions. Because they are functions, you can pass Generics `<T>` into them to guarantee they behave exactly how you expect.

Real World Example

Typing a Context API Provider. You create `const ThemeContext = createContext<ThemeType | null>(null)`. Now, whenever any component calls `useContext(ThemeContext)`, TS knows exactly what properties are available on the theme object.

Common Use Cases

  • •Global state management (Context)
  • •DOM manipulation (Refs)
  • •Performance optimization (Memo)

Interactive Example

import { useRef, createContext, useContext } from 'react';

// --- Typing Context ---
interface Theme { mode: "light" | "dark"; }
// Initial value is null because the Provider might not wrap the component yet
const ThemeContext = createContext<Theme | null>(null);

function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) throw new Error("Must be inside ThemeProvider");
  return context; // TS now narrows this to perfectly be 'Theme', not null!
}

// --- Typing Refs ---
function TextInput() {
  // Pass the specific HTML element interface to the Generic
  const inputRef = useRef<HTMLInputElement>(null);

  const focusInput = () => {
    // Optional chaining required because .current starts as null!
    inputRef.current?.focus();
  };

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

Interview Questions

basic

  • How does TS infer types in `useMemo`?

intermediate

  • Why do we often type Context starting value as `Type | null`?

advanced

  • How do you properly type a `useRef` that targets an HTML DOM element vs a mutable value?

Flash Cards

Question

How does TS infer useMemo?

Click to reveal answer
Answer

TS infers the return type of `useMemo` directly from the return statement of the callback function you provide. You rarely need to explicitly type it.

Question

How to type DOM refs vs Mutable refs?

Click to reveal answer
Answer

If targeting the DOM: `useRef<HTMLInputElement>(null)`. Note the `null`. TS makes the `.current` property read-only because React handles attaching the element. If using it as a mutable instance variable (like an interval ID): `useRef<number | null>(null)`. Now `.current` is mutable.