javascript / intermediate
Snippet
Compound Components Pattern
The Compound Components pattern allows a parent component to share state implicitly with its children using Context. This makes the API more flexible and cleaner for the consumer, as they don't have to pass props to every child manually.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const TabsContext = React.createContext();function Tabs({ children }) {const [active, setActive] = React.useState(0);return (<TabsContext.Provider value={{ active, setActive }}>{children}</TabsContext.Provider>);}Tabs.Tab = ({ index, children }) => {const { active, setActive } = React.useContext(TabsContext);return (<buttononClick={() => setActive(index)}style={{ fontWeight: active === index ? 'bold' : 'normal' }}>{children}</button>);};
react
Breakdown
1
const TabsContext = React.createContext();
Creates a context object to hold the shared state between parent and child components.
2
Tabs.Tab = ({ index, children }) => { ... }
Attaches the sub-component directly to the main component object for better organization.
3
const { active, setActive } = React.useContext(TabsContext);
Consumes the shared state from the parent without prop drilling.