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?