Intermediate LevelReact JS & React 19
How does the Compound Components design pattern work in React?
❓ Interview Prompt: Explain Compound Components design pattern, implicit state sharing via Context, flexible component markup, and sub-component dot notation.
The Compound Components pattern allows building components that work together to form a cohesive UI unit while sharing implicit state behind the scenes:
Benefits:
•
Flexible Markup Layout: Parents can rearrange child component positions freely.
•
Implicit State: Child components ('<Select.Option>') communicate with parent ('<Select>') via Context without passing explicit props down every sub-item.
Code Implementation Example
jsx
const SelectContext = createContext();
function Select({ children, value, onChange }) {
return (
<SelectContext.Provider value={{ value, onChange }}>
<div className="select-dropdown">{children}</div>
</SelectContext.Provider>
);
}
Select.Option = function Option({ value, children }) {
const { value: selectedValue, onChange } = useContext(SelectContext);
return (
<div
className={selectedValue === value ? 'selected' : ''}
onClick={() => onChange(value)}
>
{children}
</div>
);
};
// Usage:
<Select value={selected} onChange={setSelected}>
<Select.Option value="1">Option 1</Select.Option>
</Select>;💡Implementing Compound Components pattern with implicit Context state sharing.
🎯 Interview Key Takeaway
Use the Compound Components pattern to build flexible UI components (Select, Tabs, Accordion) with shared implicit state.
#Compound Components#Design Patterns#Context API#Intermediate
Back to all React JS & React 19 Questions→