React Compound Components
Building components in React is easy. Building components that don’t make your teammates want to cry two months later? That’s the real challenge.
I remember when I first started out, I thought I was being "efficient" by making my components handle every possible scenario. I’d add a prop for this, a boolean for that, and another prop for a different style. Before I knew it, I was staring at what we call the "Apropcalypse", a component with 20+ props that was impossible to maintain.
If you want to move from "writing code that works" to "architecting systems," you need to master the Compound Component Pattern.
The Problem: The Rigid "Postcard" Component
Let’s look at a classic example: a Postcard component used in a social feed. At first, it's simple. You pass in a post object, and it renders everything.
But then, requirements change:
The Naive Approach (The "Before")
To handle this, most people start adding "flag" props:
Inside the component, you end up with a jumbled mess of conditional logic. It looks like this:
This is rigid. If a designer wants a new layout tomorrow, you have to add even more props and more if statements. It's a maintenance nightmare.
The Solution: Compound Components
Think about the native HTML <select> and <option> tags. You don’t pass an array of strings to <select>. Instead, you compose them:
The <select> tag manages the state, and the <option> tags just work with it. This is Inversion of Control. We give the power back to the person using the component to decide the structure.
Step-by-Step Implementation
1. Create the Context
We need a way for the sub-components to access the post data without passing props manually to every single one.
Recommended by LinkedIn
2. The Parent (The Wrapper)
The main component just provides the data and renders whatever children you give it.
3. The Sub-Components
Each piece of the postcard becomes a small, focused component that "grabs" what it needs from the context.
Why this is a Game Changer (The "After")
Now, look at how we handle those different screens. No flags, no booleans, just pure JSX composition.
Home Feed (Everything):
Profile Screen (No User needed):
Special Layout (Buttons at the top):
Final Thoughts for the Engineering Mind
By using this pattern, you aren't just building a component; you're building a flexible system that can grow with your app. Your future self (and your team) will thank you.
Credit : https://youtu.be/N_WgBU3S9W8
Authored by Sanket Ghormode