🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Patterns: Compound Components and Render Props

React AdvancedđŸŸĸ Free Lesson

Patterns are answers, and an answer without a question is noise. The four or five patterns that keep earning their place in React codebases each solve a specific coupling problem: state that several siblings need but only one should own, markup that must vary per call site while behavior stays fixed, and logic that is reusable even when the rendering of it is not. Learn to recognize the problem before reaching for the pattern, because the wrong abstraction costs more to remove than never having written it.

💡Start from the caller

Look at how the component will be used at three different call sites. If the usage is nearly identical, you want configuration through props. If the usage differs structurally, you want to expose composition instead. That single observation settles most design arguments.

Compound components: one owner, many parts

A compound component is really two components: a hidden owner that holds the state, and several public children that read it through context. The caller composes the visible parts in JSX, so the markup, ordering and styling stay entirely in their hands, while the state machine that decides which panel is open never leaks out.

The version below is a tab group with roving tabindex: arrow keys move focus between tabs, Home and End jump to the ends, and the selected tab owns a single boolean that every other part reads.

import { createContext, useContext, useRef, useState } from 'react';

const TabsContext = createContext(null);

export function Tabs({ defaultValue, children }) {
  const [selected, setSelected] = useState(defaultValue);

  return (
    <TabsContext.Provider value={{ selected, setSelected }}>
      <div className="tabs">
        {children}
      </div>
    </TabsContext.Provider>
  );
}

export function TabList({ children }) {
  const listRef = useRef(null);

  function focusTab(index) {
    const tabs = [...listRef.current.querySelectorAll('[role="tab"]')];
    const target = tabs[(index + tabs.length) % tabs.length];
    target.focus();
    target.click();
  }

  function onKeyDown(e) {
    const tabs = [...listRef.current.querySelectorAll('[role="tab"]')];
    const current = tabs.findIndex((t) => t.getAttribute('aria-selected') === 'true');

    if (e.key === 'ArrowRight') { e.preventDefault(); focusTab(current + 1); }
    if (e.key === 'ArrowLeft')  { e.preventDefault(); focusTab(current - 1); }
    if (e.key === 'Home') { e.preventDefault(); focusTab(0); }
    if (e.key === 'End')  { e.preventDefault(); focusTab(tabs.length - 1); }
  }

  return (
    <div ref={listRef} role="tablist" aria-orientation="horizontal" onKeyDown={onKeyDown}>
      {children}
    </div>
  );
}

export function Tab({ value, children }) {
  const { selected, setSelected } = useContext(TabsContext);
  const isSelected = selected === value;

  return (
    <button
      role="tab"
      id={`tab-${value}`}
      aria-selected={isSelected}
      aria-controls={`panel-${value}`}
      tabIndex={isSelected ? 0 : -1}
      onClick={() => setSelected(value)}
    >
      {children}
    </button>
  );
}

export function TabPanel({ value, children }) {
  const { selected } = useContext(TabsContext);
  if (selected !== value) return null;
  return (
    <div role="tabpanel" id={`panel-${value}`} aria-labelledby={`tab-${value}`} tabIndex={0}>
      {children}
    </div>
  );
}

The payoff shows up in review. Because the state lives in one place, adding a lazy-loaded panel or an animated underline requires no change to the owner. Because the markup is written by the caller, one project can render the same tabs as a pill bar and another as a sidebar without the component growing a prop for every layout variation.

Render props: the caller decides what appears

Render props invert the direction of control. The component owns the hard part, such as tracking pointer position, paginating a dataset, or computing a sorted and filtered view, and hands the result to a function the caller supplies. The function returns whatever markup that call site needs, so the reusable piece is the logic and not the pixels.

import { useMemo, useState } from 'react';

export function useSortedRows(rows, { key, direction }) {
  return useMemo(() => {
    const copy = [...rows];
    copy.sort((a, b) => {
      const av = a[key];
      const bv = b[key];
      if (av === bv) return 0;
      const order = av > bv ? 1 : -1;
      return direction === 'asc' ? order : -order;
    });
    return copy;
  }, [rows, key, direction]);
}

export function DataTable({ rows, columns, renderEmpty }) {
  const [sort, setSort] = useState({ key: columns[0].accessor, direction: 'asc' });
  const [selected, setSelected] = useState([]);
  const sorted = useSortedRows(rows, sort);

  function toggleSort(accessor) {
    setSort((s) =>
      s.key === accessor
        ? { key: accessor, direction: s.direction === 'asc' ? 'desc' : 'asc' }
        : { key: accessor, direction: 'asc' }
    );
  }

  if (!rows.length) return renderEmpty();

  return (
    <table>
      <thead>
        <tr>
          {columns.map((c) => (
            <th key={c.accessor} aria-sort={sort.key === c.accessor ? (sort.direction === 'asc' ? 'ascending' : 'descending') : 'none'}>
              <button onClick={() => toggleSort(c.accessor)}>{c.header}</button>
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {sorted.map((row) => (
          <tr key={row.id} data-selected={selected.includes(row.id)}>
            {columns.map((c) => <td key={c.accessor}>{row[c.accessor]}</td>)}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

In this shape the caller never reimplements sorting, and the table never assumes what a cell should look like. Where the caller supplies only a fallback for the empty case, a plain prop is simpler than a function, so reserve the render pattern for when the caller must contribute real markup around your data.

Higher-order components: useful, rarely the first choice

A higher-order component wraps one component and returns a new one, adding behavior such as analytics tracking, permission checks, or data injection. Its failure modes are well documented: a renamed displayName that hides the inner component in DevTools, static methods lost unless hoisted, and a wrapping layer that breaks ref forwarding and error boundaries when written carelessly.

Modern React gives you two cleaner routes to the same result. A custom hook carries the logic without touching the component tree, and composition in JSX carries the behavior without a wrapper. Reach for the higher-order form only when you must modify many existing components mechanically, such as instrumenting every route in a legacy app during a migration.

Container and presentation, revisited

The oldest pattern in the list is still the most reliable structural rule: keep data acquisition and transformation in a container, keep markup in a presentation component, and let the container pass plain serializable values down. The testability benefit alone justifies it, because a presentation component with no imports of its own renders from props in a millisecond and can be asserted on without mocks.

PatternWhat it decouplesBest signal to use itMain costPrefer instead when
Compound componentShared state from markupSeveral visible parts must stay in syncContext wiring and naming disciplineOne component with a few boolean props would do
Render propReusable logic from renderingThe output shape differs per call siteNested functions harder to scanA hook can return the values directly
Custom hookStateful logic from any componentTwo or more components need the same behaviorDebugging requires DevTools hooks supportThe logic is used exactly once
Higher-order componentBehavior from many existing componentsMechanical, widespread wrappingObscures identity and breaks staticsComposition in JSX is still possible
Container and presentationData fetching from markupThe view is worth testing in isolationProp lists grow longThe component fetches nothing

Testing a pattern before trusting it

A pattern that cannot be tested without heroic setup is telling you it owns too much. The compound component above is easy to verify because the state is reachable through behavior: render the parts, press an arrow key, and assert that the panel changed. No context mocking, no reaching into the provider, no assertions about internal calls. If your test needs to import the context object directly to make an assertion, the abstraction has leaked a layer it should have kept private.

Render props test even more simply, because the reusable piece is usually a pure function of its inputs. The sorting helper in the example takes an array and a sort descriptor and returns a new array; it can be tested with a table of cases covering equal values, descending order and empty input, with no rendering at all. Keep that separation deliberately: when logic lives in a helper or a hook and only the arrangement of markup lives in the component, the expensive part of the test suite stays fast and the component test shrinks to a rendering check.

The third habit is to write the call site first. Sketch how three different features would use the component before implementing it, and the API that emerges will usually be smaller than the one you would have designed from the inside. Patterns designed from the inside accumulate optional props for cases that never arrive; patterns designed from the call site accumulate defaults, which is what makes them pleasant to use.

Choosing by the shape of the problem

Work the decision from the outside in. If two sibling components must agree about one value, lift the state or put it in context, and expose a compound API if the caller also needs to control layout. If you find yourself passing a callback three levels down, stop and consider whether a context provider or a hook on the component that actually uses it removes the drilling. If the same effect appears in two components, extract it into a hook before you extract it into a wrapper.

The strongest signal that you have chosen well is that the pattern disappears from review: reviewers talk about the feature rather than about the indirection. The strongest signal that you have chosen badly is a codebase where every component takes a render function or a configuration object with twelve optional fields, and reading one call site no longer tells you what appears on screen.

Common Mistakes

Building a compound component API for something a single component with three props handles fine

Fix: Compose first and split into owner plus parts only when callers genuinely need to arrange the pieces differently.

Passing a render function where the caller only needs a value

Fix: Return the value from a hook or prop and keep the JSX in the component, so the call site stays readable.

Extracting a pattern before it has appeared a second time

Fix: Wait for the second real use case, then extract the part that is identical and leave the variation behind a prop.

Wrapping components with a higher-order component that drops statics and refs

Fix: Use a custom hook or compose in JSX, and if you must wrap, forward refs and hoist static properties.

Key Takeaways

  • Compound components hide state behind context while leaving markup composition to the caller
  • Render props reuse logic whose output shape varies per call site, and degrade to plain props when it does not
  • Custom hooks replaced most higher-order components because they add no wrapper layer to the tree
  • Container and presentation remains the cheapest way to make markup testable in isolation
  • Choose a pattern only after seeing the problem twice, and prefer the option that keeps the call site obvious
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement