DEV Community

Priyanka-Chettri
Priyanka-Chettri

Posted on

The React Pattern That Changed How I Build Reusable Components

While building components for a design system, I initially followed an existing pattern that was already in place- they all had a consistent pattern. I didn’t know what it was called, but I loved how scalable and flexible it felt.

Later, I realized… this approach had a name — the Compound Component Pattern

Let me explain with a simple example 👇

Imagine we have a Flyout Button that, when clicked, opens a menu with a list.

Flyout with menu

Now, in a typical setup, if we want the Flyout to appear over a specific component, we’d probably pass a prop like toggle from the parent and control it there.
That works — but what if we want to use this Flyout anywhere in the app, with any icon, and in multiple combinations?

That’s where the Compound Pattern comes into play.

🧩 How to Identify When to Use It

  1. If there’s a shared state between two or more components, that shared state lives in the parent component

  2. You want flexibility and reusability without passing props down multiple levels

  3. You’d rather use React Context to manage state than prop drilling

Then you’re probably looking at a perfect use case for the Compound Design Pattern.

A component with compound pattern in action looks like this

<Flyout>
  <Flyout.Toggle>
    <Icon name="more" />
  </Flyout.Toggle>
  <Flyout.Menu>
    <Flyout.Item>Profile</Flyout.Item>
    <Flyout.Item>Settings</Flyout.Item>
    <Flyout.Item>Logout</Flyout.Item>
  </Flyout.Menu>
</Flyout>
Enter fullscreen mode Exit fullscreen mode

Here, each sub-component (Toggle, Menu, Item) communicates through a shared context, not props.
This makes the component incredibly reusable, readable, and extensible — a win for design systems.

This pattern truly changed how I think about building components in React.
Once you start using the Compound Pattern, you realize it’s not just about cleaner code — it’s about creating a language for your UI.

Top comments (0)