---
name: react-composition
description: >-
React component composition patterns for building flexible, maintainable
UIs. Covers compound components, context-based state, explicit variants,
and React 19 APIs. Use when designing component APIs, refactoring
prop-heavy components, or building reusable component libraries.
---
# React Composition
Build flexible component APIs through composition instead of configuration.
## Core Principle
**Composition over configuration.** When a component needs a new behavior, the answer is almost never "add a boolean prop." Instead, compose smaller pieces together.
```tsx
// BAD: Boolean prop explosion
// GOOD: Compose what you need
Settings...
```
## Pattern 1: Compound Components
Share implicit state through context. Each sub-component is independently meaningful.
```tsx
// 1. Define shared context
interface TabsContextValue {
activeTab: string;
setActiveTab: (tab: string) => void;
}
const TabsContext = createContext(null);
function useTabs() {
const ctx = use(TabsContext); // React 19
if (!ctx) throw new Error('useTabs must be used within ');
return ctx;
}
// 2. Root component owns the state
function Tabs({ defaultTab, children }: { defaultTab: string; children: React.ReactNode }) {
const [activeTab, setActiveTab] = useState(defaultTab);
return (