Custom hooks solved reusing logic. This chapter is about the other half of reuse: the shape of a component's API. How does a reusable component let callers decide what goes inside it, share state with its own pieces, or hand control of its state to a parent?
The patterns here have names interviewers expect you to know: slots, compound components, render props, higher-order components, headless components, controlled and uncontrolled APIs, polymorphic as props. Some are older than hooks and mostly replaced by them; some are more useful than ever. By the end you should be able to say which is which, and why.
The problem: a component that grows a prop for everything#
Here's a dialog that started simple and then got a prop for every request:
<Dialog
title="Delete book?"
subtitle="This can't be undone."
icon="warning"
showCloseButton
primaryLabel="Delete"
primaryVariant="danger"
onPrimary={remove}
secondaryLabel="Cancel"
onSecondary={close}
footerAlign="right"
bodyText="The book and its notes will be removed."
/>Every new design needs a new prop: two lines of body text, a link in the subtitle, a third button, a checkbox in the footer. The component turns into a pile of conditionals, and callers still can't do anything its author didn't predict. The props describe the content through configuration, when JSX was already a perfectly good language for describing content.
Composition and slots#
The fix is to let callers pass UI in. Every component already has one slot, children. When you need more than one region, add more props that take ReactNode (anything React can render). People call these slots.
import type { ReactNode } from "react";
function Dialog({ title, footer, children }: { title: ReactNode; footer?: ReactNode; children: ReactNode }) {
return (
<section role="dialog" aria-label={typeof title === "string" ? title : undefined} style={{ border: "1px solid #d6d3d1", borderRadius: 8, padding: 12, maxWidth: 360 }}>
<h3 style={{ marginTop: 0 }}>{title}</h3>
<div>{children}</div>
{footer ? <footer style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 12 }}>{footer}</footer> : null}
</section>
);
}
export default function App() {
return (
<Dialog
title="Delete book?"
footer={
<>
<label style={{ marginRight: "auto" }}>
<input type="checkbox" /> Also delete notes
</label>
<button>Cancel</button>
<button style={{ color: "#b4532a" }}>Delete</button>
</>
}
>
<p>
<strong>Refactoring</strong> will be removed from your reading list. <a href="#undo">Learn about undo</a>.
</p>
</Dialog>
);
}The dialog now owns only what it should own: the frame, the layout and the accessibility role. A checkbox in the footer needed no new prop. This is plain composition, and it's the first thing to reach for. It also fixes a lot of prop drilling for free: if a deep child needs user, the top-level component can often build that child itself and pass it down as children, so the layers in between never see user.
Compound components#
Slots break down when the pieces need to talk. Tabs are the classic case: the tab buttons and the panels share one piece of state (which tab is active). A configuration version (<Tabs items={[{ label, content }]} />) works until someone wants an icon in one label, or a panel that's lazy, or a badge between two tabs.
Compound components are a set of components designed to be used together, like <select> and <option>. The parent owns the state and shares it with its pieces through context, so the pieces work wherever they end up in the tree.
import { createContext, use, useState, type ReactNode } from "react";
type TabsState = { value: string; setValue: (v: string) => void };
const TabsContext = createContext<TabsState | null>(null);
function useTabs() {
const ctx = use(TabsContext);
if (!ctx) throw new Error("Tabs.Tab and Tabs.Panel must be used inside <Tabs>.");
return ctx;
}
function Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {
const [value, setValue] = useState(defaultValue);
return <TabsContext value={{ value, setValue }}>{children}</TabsContext>;
}
function List({ children }: { children: ReactNode }) {
return <div role="tablist" style={{ display: "flex", gap: 4 }}>{children}</div>;
}
function Tab({ value, children }: { value: string; children: ReactNode }) {
const tabs = useTabs();
const selected = tabs.value === value;
return (
<button role="tab" aria-selected={selected} onClick={() => tabs.setValue(value)} style={{ fontWeight: selected ? 700 : 400 }}>
{children}
</button>
);
}
function Panel({ value, children }: { value: string; children: ReactNode }) {
const tabs = useTabs();
return tabs.value === value ? <div role="tabpanel">{children}</div> : null;
}
Tabs.List = List;
Tabs.Tab = Tab;
Tabs.Panel = Panel;
export { Tabs };The caller writes ordinary JSX, wraps panels in their own div, puts a badge in a label, and the pieces still find their state. Note the error thrown by useTabs: a compound piece used outside its parent should fail loudly with a message, not render garbage.
Tabs owns the state (which tab is active) and provides it, with a setter, through context. The children are whatever the user wrote, including their own wrapper div.
Controlled and uncontrolled component APIs#
The Tabs above keeps its own state. That's convenient until the parent needs to drive it: switch tabs from a URL, open the "Done" tab after the user finishes a book, or reset it. Native inputs solved this long ago, and React copies their vocabulary (the forms chapter covers the input side):
- Uncontrolled: the component owns its state. The caller can set a starting value with
defaultValueand forget about it. - Controlled: the caller owns the state. It passes
value, listens toonChange(oronValueChange), and the component renders whatevervaluesays.
A good reusable component supports both, with one rule: the mode is decided by whether value is defined, and it shouldn't switch over the component's life. The usual implementation is a small hook:
import { useState } from "react";
export function useControllableState<T>(
value: T | undefined,
defaultValue: T,
onChange?: (next: T) => void,
) {
const [internal, setInternal] = useState(defaultValue);
const isControlled = value !== undefined;
const current = isControlled ? value : internal;
function setValue(next: T) {
if (!isControlled) setInternal(next); // uncontrolled: we own it
onChange?.(next); // either way, tell the caller
}
return [current, setValue] as const;
}Inside Tabs, useState(defaultValue) becomes useControllableState(props.value, props.defaultValue, props.onValueChange), and nothing else changes. In controlled mode the component never writes its own state; it asks the parent, and the parent's next render brings the new value.
Disclosure claims to support open / onOpenChange (controlled) and defaultOpen (uncontrolled). Clicking a header looks fine, but "Open all" and "Close all" do nothing. Fix Disclosure so both modes work. Press Check.
import { useState, type ReactNode } from "react";
type Props = {
title: string;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
children: ReactNode;
};
export function Disclosure({ title, open, defaultOpen = false, onOpenChange, children }: Props) {
const [isOpen, setIsOpen] = useState(open ?? defaultOpen);
function toggle() {
setIsOpen(!isOpen);
onOpenChange?.(!isOpen);
}
return (
<div style={{ borderBottom: "1px solid #e7e5e4", padding: "4px 0" }}>
<button aria-expanded={isOpen} onClick={toggle}>{title}</button>
{isOpen ? <p>{children}</p> : null}
</div>
);
}Render props#
A render prop is a prop whose value is a function that returns UI. The component calls it with some data and renders the result. Two very different uses hide under the one name.
The first is still everywhere: letting the caller render an item the component positions. Lists, tables, virtualized lists, autocompletes. The component owns iteration, layout and keys; the caller owns what one item looks like.
import { useState, type ReactNode } from "react";
import { books } from "guide-tools";
type Book = (typeof books)[number];
// 1. Still idiomatic: the caller decides how an item looks.
function BookList({ items, renderItem }: { items: Book[]; renderItem: (book: Book) => ReactNode }) {
if (items.length === 0) return <p>Nothing here.</p>;
return <ul>{items.map((b) => <li key={b.id}>{renderItem(b)}</li>)}</ul>;
}
// 2. The pre-hooks way to share logic: a component that only provides data.
function Toggle({ children }: { children: (state: { on: boolean; toggle: () => void }) => ReactNode }) {
const [on, setOn] = useState(false);
return <>{children({ on, toggle: () => setOn((o) => !o) })}</>;
}
export default function App() {
return (
<Toggle>
{({ on, toggle }) => (
<>
<button onClick={toggle}>{on ? "Show all" : "Only before 2000"}</button>
<BookList
items={on ? books.filter((b) => b.year < 2000) : books}
renderItem={(b) => (
<>
<strong>{b.title}</strong> <small>{b.year}</small>
</>
)}
/>
</>
)}
</Toggle>
);
}The second use, <Toggle>{({ on, toggle }) => ...}</Toggle>, was how libraries shared logic before hooks: a component with no UI of its own that hands state to a function. It works, but every piece of shared logic adds a level of nesting, and three of them produce the "pyramid" that made people unhappy in 2018. Today you'd write const { on, toggle } = useToggle() and keep your JSX flat. So: render props for rendering, hooks for logic.
Higher-order components#
A higher-order component (HOC) is a function that takes a component and returns a new component, usually wrapping it to add props or behavior. Before hooks, it was the main way to share logic across class components: connect(mapState)(Component) in Redux, withRouter(Component) in React Router.
import type { ComponentType } from "react";
import { useOnlineStatus } from "./useOnlineStatus";
// Adds an isOnline prop to any component.
function withOnlineStatus<P extends object>(Component: ComponentType<P & { isOnline: boolean }>) {
function WithOnlineStatus(props: P) {
const isOnline = useOnlineStatus();
return <Component {...props} isOnline={isOnline} />;
}
WithOnlineStatus.displayName = `withOnlineStatus(${Component.displayName ?? Component.name})`;
return WithOnlineStatus;
}
const SaveButtonWithStatus = withOnlineStatus(SaveButton);The costs are why hooks replaced HOCs for logic:
- Indirection. Reading
SaveButton, you can't see whereisOnlinecomes from. Stack five HOCs and DevTools shows five wrapper layers ("wrapper hell"). - Prop collisions. Two HOCs that both inject
datasilently overwrite each other. - Static typing is awkward. Getting the injected and outer props right in TypeScript takes the generics above, and gets worse with each layer.
- Boilerplate around the wrapper. Before React 19 you also had to forward refs with
forwardRef, hoist statics, and setdisplayName. Since React 19,refis a regular prop for function components, so spreading{...props}passes it through.
HOCs aren't dead. They still fit when you want to wrap a component as a value: memo(Component) (Memoization) is a HOC, and so are wrappers that add an error boundary, a feature flag or instrumentation around any component. What fell out of favor is using them to inject data that a hook could provide.
Type your name in the input, then click "Re-render App". What happens to the text, and why?
import { useState, type ComponentType } from "react";
function withBorder<P extends object>(Component: ComponentType<P>) {
return function Bordered(props: P) {
return (
<div style={{ border: "1px solid #a8a29e", padding: 8, marginTop: 8 }}>
<Component {...props} />
</div>
);
};
}
function NameInput() {
const [name, setName] = useState("");
return <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" />;
}
export default function App() {
const [ticks, setTicks] = useState(0);
const BorderedInput = withBorder(NameInput); // created during render
return (
<>
<button onClick={() => setTicks((t) => t + 1)}>Re-render App ({ticks})</button>
<BorderedInput />
</>
);
}Headless components#
Design systems kept hitting the same wall: a dropdown's behavior (keyboard navigation, focus, ARIA attributes, click-outside) is hard to get right, and its look is different in every product. A headless component gives you the behavior and accessibility with no markup or styles. You bring the elements.
There are two shapes in the wild:
- Headless hooks return state plus prop getters: functions that return the props an element needs. Downshift's
useComboboxand TanStack Table work this way. - Unstyled compound components ship the elements but no styles: Radix UI primitives, React Aria Components, Headless UI. Many design systems (shadcn/ui, for example) are styled layers over these.
Here's a tiny headless hook. It owns open state, ids and ARIA wiring. The markup is entirely the caller's.
import { useId, useState } from "react";
export function useDisclosure(defaultOpen = false) {
const [open, setOpen] = useState(defaultOpen);
const id = useId();
const panelId = id + "-panel";
return {
open,
// Prop getters: spread them onto whatever elements you like.
getToggleProps: () => ({
"aria-expanded": open,
"aria-controls": panelId,
onClick: () => setOpen((o) => !o),
}),
getPanelProps: () => ({ id: panelId, hidden: !open }),
};
}Headless is where the patterns in this chapter meet. The logic is a custom hook; the parts are often compound components; the open state is usually controllable; and the rendering is left to the caller, which is what render props were reaching for.
Polymorphic components: the as prop#
A Button that sometimes needs to be a link, or a Text that renders h2, p or span, is usually written with an as prop. The runtime part is one line: a variable holding a component type, capitalized so JSX treats it as a component.
import type { ComponentPropsWithoutRef, ElementType, ReactNode } from "react";
type TextProps<C extends ElementType> = {
as?: C;
tone?: "default" | "muted";
children?: ReactNode;
} & Omit<ComponentPropsWithoutRef<C>, "as" | "tone" | "children">;
export function Text<C extends ElementType = "span">({ as, tone = "default", ...rest }: TextProps<C>) {
const Component = as ?? "span";
return <Component data-tone={tone} {...rest} />;
}The typing is the interesting part. C is inferred from as, and ComponentPropsWithoutRef<C> pulls in exactly the props that element accepts. So TypeScript knows that as="a" allows href and as="label" allows htmlFor:
<Text as="a" href="/books">All books</Text> // ok
<Text as="label" htmlFor="q">Search</Text> // ok
<Text as="h2" href="/books">Title</Text> // error: 'href' does not exist on h2 props(The sandbox strips types without checking them, so this one is static.) If you need refs, use ComponentPropsWithRef<C> instead, since ref is a normal prop in React 19.
The trade-off: polymorphic types are slow for the TypeScript checker and produce long error messages, and as invites invalid HTML (a button inside an a). Radix popularized an alternative, asChild: the component merges its props onto the single child you pass (<Button asChild><a href="/books">All books</a></Button>), so you write the real element yourself. Either is fine; know both names.
Which patterns hooks replaced#
- Mixins (the
createClassera) shared logic by merging methods into a class. They collided on names and hid dependencies. Hooks replaced them completely. - HOCs for injecting data (
withRouter,connect): replaced by hooks (useNavigate,useSelector). HOCs that wrap a component as a value (memo, error boundary wrappers) remain. - Render props for sharing logic (
<Toggle>{(on) => ...}</Toggle>): replaced by hooks. Render props for rendering an item (renderItem, table cells) remain idiomatic. - cloneElement-based compound components: replaced by context, which works through wrappers.
- Unchanged and more common than ever: composition and slots, compound components, controlled and uncontrolled APIs, headless components.
The reason is the same each time. Hooks let a component call reusable logic in its own body, so the logic doesn't need its own component layer. Every layer an older pattern added (wrapper components, nested functions, cloned children) existed only because there was nowhere else to put state.
Pitfalls#
Check your understanding#
A Select component must let callers put icons and dividers between options, and options must know which one is selected. Which pattern fits best?
An interviewer asks: "Before hooks we had HOCs and render props. What problems did they have, and are they still useful?"
An interviewer asks: "You're designing a reusable Tabs component. Should it be controlled or uncontrolled?"
Interview angle
Component patterns are about the shape of a reusable component's API. Start with composition: children and slot props let callers pass UI instead of configuring it. Compound components, like Tabs with Tab and Panel, share state through context so the pieces work anywhere in the tree. Good components support controlled (value plus onChange) and uncontrolled (defaultValue) modes. Hooks replaced mixins, HOCs and render props for sharing logic, because they remove the extra component layer; render props survive for rendering items, HOCs for wrapping components like memo. Headless components ship behavior and accessibility without markup.
What are compound components and how do you implement them?
How do you design a component that can be both controlled and uncontrolled?
Why did hooks replace higher-order components for most uses? When would you still write a HOC?
Are render props still relevant?
What is a headless component, and why have design systems moved toward them?
A shared Dialog component has grown 15 props: title, subtitle, icon, primaryLabel, footerAlign and so on. Every new design adds another. What would you change?
Recap#
- Prefer composition:
childrenand slot props of typeReactNodelet callers pass UI instead of configuring it through props. - Compound components share state through context, so the pieces work wherever the caller puts them. Throw a helpful error when a piece is used outside its parent.
- Support controlled (
valueandonChange) and uncontrolled (defaultValue) modes, choose the mode fromvalue !== undefined, and never copy a controlled prop into state. - Render props remain idiomatic for rendering items; HOCs remain for wrapping a component as a value. For sharing logic, hooks replaced both, along with mixins.
- Headless components ship behavior and accessibility without markup. A typed
asprop (orasChild) makes a component render as a different element.
Sources#
- react.dev: Passing JSX as children
- react.dev: Scaling up with reducer and context
- react.dev: Sharing state between components: controlled and uncontrolled components
- react.dev: Legacy React APIs: cloneElement and Children
- react.dev: React 19: ref as a prop
- Facts checked November 24, 2026.