What is the Compound Component pattern?

EasyComponent PatternsTheory Question

Hint

Related components share implicit state via context — like <select> and <option> in HTML

Full Answer

Compound components work together, sharing state implicitly through context. The parent manages state; children access it without explicit prop passing.

const TabsContext = createContext(null);

function Tabs({ children, defaultTab }) {
  const [active, setActive] = useState(defaultTab);
  return (
    <TabsContext.Provider value={{ active, setActive }}>
      <div>{children}</div>
    </TabsContext.Provider>
  );
}

function TabList({ children }) {
  return <div role="tablist">{children}</div>;
}

function Tab({ id, children }) {
  const { active, setActive } = useContext(TabsContext);
  return (
    <button
      role="tab"
      aria-selected={active === id}
      onClick={() => setActive(id)}
    >
      {children}
    </button>
  );
}

function TabPanel({ id, children }) {
  const { active } = useContext(TabsContext);
  return active === id ? <div role="tabpanel">{children}</div> : null;
}

// Usage — clean, flexible, no prop drilling
<Tabs defaultTab="profile">
  <TabList>
    <Tab id="profile">Profile</Tab>
    <Tab id="settings">Settings</Tab>
  </TabList>
  <TabPanel id="profile"><ProfileView /></TabPanel>
  <TabPanel id="settings"><SettingsView /></TabPanel>
</Tabs>
💡 Good examples: Tabs, Accordion, Dropdown, Form with Field/Label/Error subcomponents. The key insight — the developer using the component controls the structure; the component controls the behavior.

More Component Patterns Questions

Practice this in a timed sprint

5 free questions, no signup required