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

Loading Code Playground...

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.