The React Pattern You Never Heard of That You Should Be Using

Brian Jenney
3 min readJul 16, 2023

--

I’m going to show you how to make your React codebase more flexible and less complex by leveraging a little known pattern for React components: The Compound Components pattern.

Implementing the Compound Components pattern gives you the ability to create components that can be reused in different ways, without adding lots of if else statements.

This will make your code easier to maintain and understand and maybe even impress your team mates.

Unfortunately, most developers don’t know this pattern exists!

Step 1: Understand What Compound Components Are

The first step is recognizing what Compound Components are and their value.

The Compound Components pattern is a design pattern in which components are used together so they can share state, allowing them to communicate with each other but are loosely coupled. One of its hallmarks is the use of static properties on a component. Basically dot notation for accessing nested components.

Think of a component that looks like an object.

Step 2: Identify Where to Apply the Pattern

When all you have is a hammer, everything looks like a nail. To be a great developer, you need to know what tool to use for the job.

The Compound Components pattern really shines when components have a clear parent-child relationship and share state or functionality. This pattern allows different instances of a component to have different ordering or composition, offering increased flexibility.

Consider a typical Cart component in an e-commerce application. Before applying the Compound Components pattern, you might have something like this:

function Cart({ items, total }) {
return (
<div>
{items.map(item =>
<CartItem key={item.id} item={item} />
)}
<CartTotal total={total} />
</div>
);
}

In this example, every instance of the Cart component will have the same structure, and customizing the order of the CartItem components or omitting the CartTotal component can lead to messy conditional logic.

--

--

Brian Jenney

full-stackish developer, late bloomer coder and power google user and owner of Parsity.io