React Design Patterns Interview Questions: HOC, Render Props, Compound Components and More
12 React design pattern interview questions with code: composition vs inheritance, container and presentational components, controlled vs uncontrolled, higher-order components, render props, custom hooks, compound components, forwardRef, error boundaries and folder structure.
Once you can build components, interviewers ask how you'd make them reusable and maintainable. React patterns are proven ways to share logic and structure UI. This post covers 12 React design pattern interview questions, each with an answer, code and when to use the pattern.
Composition basics#
Q1. Why does React prefer composition over inheritance?#
Answer: React components are reused by combining them, not by extending classes. Using children and props that accept elements, a generic component can wrap any content without knowing what it is. The React team has said they haven't found use cases where component inheritance hierarchies are needed.
function Card({ title, actions, children }) {
return (
<div className="card">
<header>{title}{actions}</header>
<div className="card-body">{children}</div>
</div>
);
}
<Card title="Profile" actions={<button>Edit</button>}>
<Avatar user={user} />
</Card>Q2. What are container and presentational components?#
Answer: the pattern splits components by responsibility:
- Presentational: how things look. Receive data via props, have little or no state, easy to reuse and test (and to show in Storybook).
- Container: how things work. Fetch data, manage state and pass it down.
// Presentational
function UserList({ users, onSelect }) {
return users.map((u) => <li key={u.id} onClick={() => onSelect(u)}>{u.name}</li>);
}
// Container (logic in a custom hook)
function UserListContainer() {
const { data: users = [] } = useUsers();
const navigate = useNavigate();
return <UserList users={users} onSelect={(u) => navigate(`/users/${u.id}`)} />;
}With hooks, the strict split matters less: logic often moves into a custom hook instead of a container component. The idea of separating logic from markup is still useful.
Q3. What is the difference between controlled and uncontrolled components?#
// Controlled: React state is the source of truth
function ControlledInput() {
const [email, setEmail] = useState("");
return <input value={email} onChange={(e) => setEmail(e.target.value)} />;
}
// Uncontrolled: the DOM holds the value; read it with a ref
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = () => console.log(inputRef.current.value);
return <input ref={inputRef} defaultValue="" />;
}| Controlled | Uncontrolled | |
|---|---|---|
| Value stored in | React state | The DOM |
| Instant validation / formatting | Easy | Harder |
| Re-renders per keystroke | Yes | No |
| Used by | Most custom forms | File inputs, React Hook Form, simple forms |
The same idea applies to your own components: a Tabs component can be controlled (activeTab and onChange props) or uncontrolled (manages its own state, with a defaultTab).
Sharing logic#
Q4. What is a higher-order component (HOC)?#
Answer: a HOC is a function that takes a component and returns a new component with extra behaviour. It was the main way to share logic before hooks.
function withAuth(Component) {
return function AuthenticatedComponent(props) {
const { user, isLoading } = useAuth();
if (isLoading) return <Spinner />;
if (!user) return <Navigate to="/login" />;
return <Component {...props} user={user} />;
};
}
const ProtectedDashboard = withAuth(Dashboard);Downsides: "wrapper hell" in devtools, prop name collisions between HOCs, and it's unclear where a prop came from. Still seen in React.memo, older Redux connect and route guards.
Q5. What is the render props pattern?#
Answer: a component takes a function as a prop (often children) and calls it with data, letting the caller decide what to render.
function MouseTracker({ children }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })}>
{children(pos)}
</div>
);
}
<MouseTracker>
{({ x, y }) => <p>Mouse at {x}, {y}</p>}
</MouseTracker>It avoids HOC prop collisions, but nested render props become hard to read. You still see it in libraries like Formik, Downshift and React Router's older APIs.
Q6. Why have custom hooks replaced most HOCs and render props?#
function useMousePosition() {
const [pos, setPos] = useState({ x: 0, y: 0 });
useEffect(() => {
const handler = (e) => setPos({ x: e.clientX, y: e.clientY });
window.addEventListener("mousemove", handler);
return () => window.removeEventListener("mousemove", handler);
}, []);
return pos;
}
function Cursor() {
const { x, y } = useMousePosition();
return <p>Mouse at {x}, {y}</p>;
}| Pattern | Extra component in the tree? | Clear data source? | Composes easily? |
|---|---|---|---|
| HOC | Yes | No | Wrapper nesting |
| Render props | Yes | Yes | Callback nesting |
| Custom hook | No | Yes | Just call several hooks |
More hook examples are in React hooks interview questions.
Flexible component APIs#
Q7. What are compound components? Build an Accordion#
Answer: compound components are a set of components that work together and share implicit state through context, like <select> and <option>. The user controls structure and order; the parent controls behaviour.
const AccordionContext = createContext(null);
function Accordion({ children }) {
const [openId, setOpenId] = useState(null);
return (
<AccordionContext.Provider value={{ openId, setOpenId }}>
<div className="accordion">{children}</div>
</AccordionContext.Provider>
);
}
function AccordionItem({ id, title, children }) {
const { openId, setOpenId } = useContext(AccordionContext);
const isOpen = openId === id;
return (
<div>
<button aria-expanded={isOpen} onClick={() => setOpenId(isOpen ? null : id)}>
{title}
</button>
{isOpen && <div>{children}</div>}
</div>
);
}
Accordion.Item = AccordionItem;
// Usage
<Accordion>
<Accordion.Item id="1" title="Shipping">Ships in 2 days</Accordion.Item>
<Accordion.Item id="2" title="Returns">30-day returns</Accordion.Item>
</Accordion>Compare with a "prop soup" API like <Accordion items={[...]} renderTitle={...} titleClassName="..." />, which grows a new prop for every customisation.
Q8. How do you forward a ref to a child DOM element?#
// React 18 and earlier
const TextInput = forwardRef(function TextInput(props, ref) {
return <input ref={ref} className="input" {...props} />;
});
// React 19: ref is a regular prop for function components
function TextInput({ ref, ...props }) {
return <input ref={ref} className="input" {...props} />;
}
function Form() {
const inputRef = useRef(null);
return (
<>
<TextInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</>
);
}Answer: reusable inputs and buttons should forward refs so parents can focus or measure them. useImperativeHandle lets you expose a limited API (for example, only focus()) instead of the whole DOM node.
Q9. What is the props getter / polymorphic "as" prop pattern?#
// Polymorphic component: render as any element
function Button({ as: Component = "button", ...props }) {
return <Component className="btn" {...props} />;
}
<Button onClick={save}>Save</Button>
<Button as="a" href="/docs">Docs</Button>Answer: the as prop lets one styled component render as different elements, keeping correct semantics (a link is an <a>, not a button with a click handler). Design-system libraries like Chakra and MUI use it. Prop getters (getInputProps()) return the props a user should spread onto their own elements, as Downshift does.
Robustness and structure#
Q10. What is an error boundary?#
Answer: an error boundary catches JavaScript errors during rendering in its child tree and shows a fallback UI instead of unmounting the whole app. It must be a class component (or use a library like react-error-boundary).
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info.componentStack);
}
render() {
if (this.state.hasError) return this.props.fallback;
return this.props.children;
}
}
<ErrorBoundary fallback={<p>Chart failed to load.</p>}>
<RevenueChart />
</ErrorBoundary>It does not catch errors in event handlers, async code (setTimeout, promises) or the boundary itself; handle those with try/catch.
Q11. What is the provider pattern, and what is a common mistake with it?#
Answer: a provider component holds shared state and exposes it through context, usually with a custom hook as the only way to read it (see the useCart example in React state management interview questions). Common mistakes:
- Putting everything in one giant provider, so every consumer re-renders on any change.
- Creating a new value object every render without
useMemo. - Not throwing a helpful error when the hook is used outside its provider.
Q12. How do you structure folders in a large React project?#
src/
app/ # routing, providers, app shell
features/
cart/
components/ # CartItem, CartSummary
hooks/ # useCart
api.ts # cart API calls
index.ts # public exports for the feature
auth/
shared/
ui/ # Button, Modal, Input (design system)
lib/ # utilities, formatters
hooks/ # generic hooks (useDebounce)Answer: group by feature rather than by file type once the app grows. Everything about a feature lives together, so it's easy to find, change and delete. Shared, generic pieces go in a shared folder, and features import each other only through their public index file.
Quick revision#
| Pattern | Use it for |
|---|---|
| Composition / children | Generic layout components (Card, Modal) |
| Container / presentational | Separating data logic from markup |
| Controlled component | Parent owns the value |
| HOC | Wrapping components (auth guards, memo) |
| Render props | Caller decides what to render with shared data |
| Custom hook | Sharing stateful logic (default choice) |
| Compound components | Flexible multi-part UI (Tabs, Accordion, Menu) |
| Error boundary | Isolating rendering failures |
Key takeaways#
- React reuses UI through composition, not inheritance.
- Custom hooks are the default way to share logic; HOCs and render props still appear in libraries and older code.
- Compound components give flexible APIs without dozens of configuration props.
- Forward refs from reusable inputs and wrap risky sections in error boundaries.
- Organise large apps by feature, with a shared folder for generic UI and utilities.