MyInternships.in

Performance & Patterns

React Compound Components Pattern

Compound components are a set of components designed to work together, sharing implicit state through context — the way <select> and <option> relate in HTML. The caller controls the markup while the group handles the behaviour.


What is Compound Components Pattern in React?

Compound components are a set of components designed to work together, sharing implicit state through context — the way <select> and <option> relate in HTML. The caller controls the markup while the group handles the behaviour.

Compound Components Pattern example

A tabs component
JSX
const TabsContext = createContext(null);

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

Tabs.Tab = function Tab({ id, children }) {
  const { active, setActive } = useContext(TabsContext);
  return (
    <button className={active === id ? 'tab on' : 'tab'} onClick={() => setActive(id)}>
      {children}
    </button>
  );
};

Tabs.Panel = function Panel({ id, children }) {
  const { active } = useContext(TabsContext);
  return active === id ? <div>{children}</div> : null;
};

<Tabs defaultTab="jd">
  <Tabs.Tab id="jd">Description</Tabs.Tab>
  <Tabs.Tab id="co">Company</Tabs.Tab>
  <Tabs.Panel id="jd">…</Tabs.Panel>
</Tabs>

Key points to remember

  • Flexible markup without a long list of configuration props.
  • Throw a clear error when a sub-component is used outside its parent.
  • The pattern behind Radix UI, Headless UI and most component libraries.

React Compound Components Pattern— Interview Questions & FAQs

When are compound components worth it?+

When a component has several coordinated parts and callers need control over layout and ordering — tabs, accordions, menus, selects. For a single-purpose component, plain props are simpler.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships