React·Intermediate·Coding·1 min read
How do compound components typically share state between their pieces?
Short interview answer
Through React context — a parent component like Tabs creates the shared state and a context provider, and its associated sub-components like Tabs.List and Tabs.Tab consume that context instead of receiving the state threaded through explicit props.
Example
const TabsCtx = createContext(null);function Tabs({ children }) { const [active, setActive] = useState(0); return <TabsCtx.Provider value={{ active, setActive }}>{children}</TabsCtx.Provider>;}Tabs.Tab = function Tab({ index, children }) { const { active, setActive } = useContext(TabsCtx); return <button aria-selected={active === index} onClick={() => setActive(index)}>{children}</button>;};Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.