What are the patterns for sharing logic between components in React?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
Answer
React has evolved through several patterns for sharing component logic, each with different tradeoffs. (1) Custom Hooks (modern, preferred): extract stateful logic into a reusable "use..." function. No component wrapping, no props collision, no render tree pollution. Best for: any sharable stateful logic. (2) Higher-Order Components (HOCs): function that wraps a component, adding behavior. Problems: wrapper hell in DevTools, prop name collisions, unclear origin of props. Legacy pattern — hooks usually replace it. (3) Render Props: component that accepts a function prop to render. More explicit than HOCs but creates callback nesting. (4) Context: shares state/logic down the tree without props. Good for global concerns (auth, theme) but re-render issues for dynamic data. (5) Compound Components: multiple components sharing state via context, composable API. Best for UI component libraries. (6) State Management Libraries (Redux, Zustand, Jotai): globally accessible logic and state. (7) Suspense + use() (React 19): share async data fetching logic declaratively. Decision: custom hooks first; context for shared state; compound components for UI kits; global state libraries when context is too broad.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex React.js answers easy to follow.
Previous
What is the React Compiler (React Forget)?
Next
How does React handle accessibility (a11y)?
More React.js Questions
View all →- Advanced How does React's reconciliation algorithm handle keys?
- Advanced What is the React Fiber architecture in depth?
- Advanced What are React rendering optimizations beyond React.memo?
- Advanced How do you implement an undo/redo system in React?
- Advanced What are React's concurrent features and how do Transitions work?