Compound Component
Introduction
In React, a compound component is a design pattern used to create a group of components that work together to form a cohesive unit with a shared state and behavior. This pattern allows for greater flexibility and control over how components are composed and used, often leading to more maintainable and reusable code.i) Parent Component
The main component that holds the shared state and logic.ii) Child Components
Sub-components that rely on the parent component for state and behavior but can be used flexibly within the parent component.
iii) Context
Often used to share state and functionality between the parent and child components.Example
Let's consider an example where we create a Tabs component using the compound component pattern.// Tabs.js // Let's consider an example where we create a Tabs component using the compound component pattern. import React, { useState, createContext, useContext } from 'react'; const TabsContext = createContext(); const Tabs = ({ children }) => { const [activeTab, setActiveTab] = useState(0); return ( <TabsContext.Provider value={{ activeTab, setActiveTab }}> <div className="tabs">{children}</div> </TabsContext.Provider> ); }; export default Tabs;// TabList.js // A component that renders the list of tab buttons. import React from 'react'; import { useContext } from 'react'; import { TabsContext } from './Tabs'; const TabList = ({ children }) => { const { activeTab, setActiveTab } = useContext(TabsContext); return ( <div className="tab-list"> {React.Children.map(children, (child, index) => { return React.cloneElement(child, { isActive: index === activeTab, onClick: () => setActiveTab(index), }); })} </div> ); }; export default TabList;// Tab.js // A component that represents a single tab button. import React from 'react'; const Tab = (props) => { return ( <button className={`tab ${props.isActive ? 'active' : ''}`} onClick={props.onClick} > {props.children} </button> ); }; export default Tab;// App.js // The main application component that uses the Tabs compound component. import React from 'react'; import Tabs from './Tabs'; import TabList from './TabList'; import Tab from './Tab'; const App = () => { return ( <Tabs> <TabList> <Tab>Tab 1</Tab> <Tab>Tab 2</Tab> <Tab>Tab 3</Tab> </TabList> </Tabs> ); }; export default App;Advantages and Considerations
i) AdvantagesModularity
Breaks down complex components into smaller, manageable pieces.Reusability
Components can be reused in different parts of the application.Maintainability
Easier to update and maintain individual components.ii) Considerations
Complexity
The pattern can introduce additional complexity, especially for developers unfamiliar with Context or compound components.Performance
Excessive use of context or deeply nested components may have performance implications.