QuestionsReact

Compound components & render props

Component PatternsMediumReact

You're building a reusable <Tabs> (or <Accordion>) for a design system. Compare the compound-component pattern and render props for sharing state between a parent and its flexible children.

What it tests

Choosing a composition API that stays flexible without prop-drilling or leaking internals.

Approach & answer

The problem: a parent owns some state (which tab is active) and several children need to read/affect it, but you don't want the consumer to wire every child manually or drill props through markup they control. Two classic patterns. Compound components: the parent (<Tabs>) holds state and shares it with its children (<Tab>, <TabPanel>) implicitly via context, so the consumer writes natural, declarative markup and the pieces coordinate themselves — `<Tabs><Tab/><Tab/><TabPanels>...</TabPanels></Tabs>`. It reads cleanly and lets consumers reorder/wrap children freely; the cost is the implicit context coupling (a <Tab> only works inside <Tabs>). Render props (and its function-as-children variant): the component computes state and calls a function you pass, handing you the values to render however you like — `<Toggle>{({on, toggle}) => ...}</Toggle>`. Maximum flexibility and fully explicit, but nests awkwardly and can cause extra renders. In modern React, custom hooks have absorbed much of what render props/HOCs did for *logic* reuse — but render props still win when the shared thing is *rendering* control, and compound components remain the go-to for cohesive multi-part UI widgets in design systems. HOCs are the older wrapper approach (withRouter), now largely legacy.

Use this technique when

Reusable multi-part widget where children coordinate shared state → compound components (context); flexible render control → render props.

References

jsx