The Context API lets you share data with many components in a tree without passing props through every level (prop drilling). Three steps 1. Create a context import { createContext, useContext, useMemo, useState, ReactNode } from 'react'; type Theme = 'light' | 'dark'; type ThemeContextValue = { theme: Theme; toggle: () => void }; const ThemeContext = createContext<ThemeContextValue | null>(null); 2. Provide a value export function ThemeProvider({ children }: { children: ReactNode }) { const [theme, setTheme] = useState<Theme>('light'); const value = useMemo(() => ({ theme, toggle: () => setTheme(t => (t === 'light' ? 'dark' : 'light')) }), [theme]); return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>; } (React 19 also allows <ThemeContext value={value}> without .Provider.) 3. Consume it anywhere below the provider export function useTheme() { const ctx = useContext(ThemeContext); if (!ctx) throw new Error('useTheme must be used inside ThemeProvider'); return ctx; } function Header() { const { theme, toggle } = useTheme(); return <button onClick={toggle}>Switch from {theme}</button>; } Typical uses - Theme, language and locale settings. - The authenticated user and permissions. - Feature flags and configuration. - Dependencies such as an API client. Performance considerations - Every component using a context re-renders when the provider's value changes. Memoise the value (useMemo) so it does not change on every render. - Split contexts by concern (AuthContext, ThemeContext) instead of one huge "AppContext", and separate frequently changing state from rarely changing data or functions. - Context is not a full state management library: it has no selectors, middleware or devtools. For complex, frequently updated global state, consider Redux Toolkit, Zustand or Jotai. For server data, use TanStack Query or RTK Query rather than storing API responses in context. Interview summary: "Context solves prop drilling for data many components need. I use it for app-wide settings and auth, keep values memoised and contexts small, and use dedicated libraries for complex state or server caching."
Ravindra Wadile · · 0 likes