ESC

Type to search the knowledge base.

Composition vs Inheritance

React prefers composition over inheritance: children, special slots, and why extend MyComponent is a dead end.

beginner3 min read
  • react
  • composition-vs

Class hierarchies of UI widgets sounded organized in 2015. In React they fight the model. Components are functions of props; reuse comes from composition — nesting elements, passing children, and sharing logic with hooks — not class Dialog extends Modal.

Docs: Composition vs Inheritance, Containing other components.

children as the main API

function Card({ children }) {
  return <section className="card">{children}</section>;
}

function Page() {
  return (
    <Card>
      <h2>Billing</h2>
      <p>Next invoice on Friday.</p>
      <button type="button">Pay</button>
    </Card>
  );
}

Card does not know or subclass its contents. Parents decide structure. That is the opposite of inheritance, where a base class guesses every extension point.

Named slots via props

function Modal({ title, body, footer }) {
  return (
    <div role="dialog" aria-modal="true" aria-label={title}>
      <header>{title}</header>
      <div>{body}</div>
      <footer>{footer}</footer>
    </div>
  );
}

<Modal
  title="Delete file?"
  body={<p>This cannot be undone.</p>}
  footer={
    <>
      <button type="button" onClick={onCancel}>Cancel</button>
      <button type="button" onClick={onConfirm}>Delete</button>
    </>
  }
/>

Slots are just props that accept React nodes. More flexible than forcing subclasses to override renderFooter().

Logic reuse: hooks, not superclasses

function useOnlineStatus() {
  const [online, setOnline] = useState(
    typeof navigator !== 'undefined' ? navigator.onLine : true
  );
  useEffect(() => {
    const on = () => setOnline(true);
    const off = () => setOnline(false);
    window.addEventListener('online', on);
    window.addEventListener('offline', off);
    return () => {
      window.removeEventListener('online', on);
      window.removeEventListener('offline', off);
    };
  }, []);
  return online;
}

function SaveButton() {
  const online = useOnlineStatus();
  return <button type="button" disabled={!online}>Save</button>;
}

HOCs and render props still exist for legacy code; hooks are the default. See higher-order components and render props.

Why inheritance hurts here

  • Fragile base class: change Modal lifecycle, break every subclass.
  • Hard to type and tree-shake.
  • Cross-cuts (analytics, auth) multiply intermediate classes.
  • React’s reconciliation cares about element type; subclassing does not give you a cleaner fiber tree.

Interview out-loud

“React reuses UI through composition: children, slot props, and custom hooks. Inheritance fights props-down data flow and makes extension points rigid. I wrap, nest, and extract hooks instead of extending components.”

Further reading

Production checklist

  1. Source of truth clear for every piece of UI state?
  2. Remount, route change, and Strict Mode cleanup paths handled?
  3. Urgent updates separated from deferrable work?
  4. Profiled before memo, virtualization, or context splits?
  5. Keyboard, focus, and accessible names still work after the change?

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Related guides