Context · Quick recall Q&A
1 min readRapid overview
Quick recall Q&A
Q: What is React Context and when should I use it? A: Context provides a way to share values between components without prop drilling. Use it for cross-cutting concerns like themes, auth, or locale that many components need access to.
Q: How do I prevent unnecessary re-renders with Context? A: Memoize the context value with useMemo, split contexts by update frequency, use separate state and dispatch contexts, or consider libraries like Zustand for high-frequency updates.
Q: What's the difference between Context and Redux? A: Context is built-in and simpler but lacks devtools, middleware, and optimized selectors. Redux has more features for complex state management but requires more setup. Use Context for simple sharing, Redux for complex app state.
Q: Can I have multiple contexts? A: Yes, you can nest multiple providers. Split contexts by domain (auth, theme, locale) or update frequency to optimize re-renders.
Q: How do I type Context with TypeScript? A: Use
createContext<T | undefined>(undefined) and create a custom hook that throws if context is undefined. This ensures type safety and catches missing providers.Q: Should I use Context for form state? A: Generally no. Form state is local and props/controlled components work well. Use Context only if form state needs to be accessed by deeply nested components outside the form.
Q: What's the compound component pattern? A: A pattern where a parent component shares state with children via Context. Children access shared state without prop drilling. Used for tabs, accordions, menus, etc.
Q: How do I access Context outside of React components? A: You can't use useContext outside components. Store the value in a ref, use a state management library, or restructure to keep the logic inside components.