Middle
What reuse patterns exist in React? What are Compound Components?
sobes.tech AI
Answer from AI
In React, there are different patterns for reusing components:
- HOC (Higher-Order Components) — functions that take a component and return a new one with extended functionality.
- Render Props — passing a function as a prop that returns JSX, allowing the component to manage logic, and the child to handle rendering.
- Custom Hooks — extracting logic into reusable functions that use hooks.
- Compound Components — a pattern where multiple components work together using a shared context to manage state and behavior. This allows creating flexible and declarative APIs.
Example of Compound Components:
const TabsContext = React.createContext();
function Tabs({ children }) {
const [activeIndex, setActiveIndex] = React.useState(0);
return (
<TabsContext.Provider value={{ activeIndex, setActiveIndex }}>
{children}
</TabsContext.Provider>
);
}
function TabList({ children }) {
return <div>{children}</div>;
}
function Tab({ index, children }) {
const { activeIndex, setActiveIndex } = React.useContext(TabsContext);
return (
<button
style={{ fontWeight: activeIndex === index ? 'bold' : 'normal' }}
onClick={() => setActiveIndex(index)}
>
{children}
</button>
);
}
function TabPanels({ children }) {
const { activeIndex } = React.useContext(TabsContext);
return <div>{children[activeIndex]}</div>;
}
// Usage:
// <Tabs>
// <TabList>
// <Tab index={0}>Tab 1</Tab>
// <Tab index={1}>Tab 2</Tab>
// </TabList>
// <TabPanels>
// <div>Content 1</div>
// <div>Content 2</div>
// </TabPanels>
// </Tabs>