Introduction
Compound components are a pattern commonly used in React applications where a parent component manages the state and behavior, while child components (compound components) are used to structure the UI.
In compound components, instead of passing state through props, we pass elements as children to a parent element.
Problem
Below is the FAQSection component. And we’re passing this question, answer and author to all of these properties, so this is the common situation when you create a component like this.
And inside the FAQSection component itself.
This works as expected, no problems with that. But we want to use this component in many places.
Let’s copy our component.
And we receive a request from the designer to hide the answer. What we usually do is we introduce new Flags. We introduce something like showAnaswer and we say false.
And we may also receive a request to switch the order of certain elements. Set the author to be on top. We would again introduce another Flag. As you can see we can start adding more properties and to these properties we will add the if statements and conditionals inside the FAQSection component and we’re increasing non-optimal complexity as you start adding more use cases, there will be a better way to handle this.
So let me show you how we can use the compound pattern to fix this.
Implementing the compound component
We add new properties to the functions. And instead of passing all these Properties, we just need children.
And now we can go to our app component and update it.
We want to hide the answer so what we can do easily is remove FAQSection.Answer. We don’t need to send any Properties or Flags.
When we want to switch the order of certain elements. We move FAQSection.Question below FAQSection.Author. And you see how this flexibility by allowing users to customize and configure the behavior and appearance.
Another thing that I like here is that you only import this one component but you have access to all of these child components from it.
Conclusion
In summary, compound components offer advantages in terms of code organization, maintainability, reusability, and flexibility, making them a valuable pattern for building scalable and well-structured UIs.
Would you like to read more articles by Tekos’s Team? Everything’s here.