SmartCodingTips

๐Ÿ”— Compound Components Pattern

Compound Components is a design pattern where components work together to share state and behavior, making them more expressive and flexible for users of your component library.


๐ŸŽ›๏ธ 1. What Are Compound Components?

Compound components allow multiple subcomponents to implicitly share state and logic through context, giving developers a flexible and declarative API.

๐Ÿงช 2. Example: Toggle Component


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

const ToggleContext = createContext();

function Toggle({ children }) {
  const [on, setOn] = useState(false);
  const toggle = () => setOn(!on);

  return (
    <ToggleContext.Provider value={{ on, toggle }}>
      {children}
    </ToggleContext.Provider>
  );
}

Toggle.On = function On({ children }) {
  const { on } = useContext(ToggleContext);
  return on ? children : null;
};

Toggle.Off = function Off({ children }) {
  const { on } = useContext(ToggleContext);
  return !on ? children : null;
};

Toggle.Button = function Button() {
  const { toggle } = useContext(ToggleContext);
  return (
    <button onClick={toggle} className="bg-indigo-600 text-white px-4 py-2 rounded">
      Toggle
    </button>
  );
};

โš™๏ธ 3. Usage Example


function App() {
  return (
    <Toggle>
      <Toggle.On>The toggle is ON</Toggle.On>
      <Toggle.Off>The toggle is OFF</Toggle.Off>
      <Toggle.Button />
    </Toggle>
  );
}

โœ… 4. Why Use Compound Components?

  • Cleaner and expressive usage syntax
  • State sharing across deeply nested components
  • Decouples layout and behavior
  • Great for design systems

๐Ÿ’ก 5. Best Practices

  • Use React Context internally
  • Keep API intuitive and declarative
  • Expose clear subcomponents (e.g., Toggle.Button, Toggle.On)