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?