Context: Let’s take an example of a complex product tile component with multiple child components which dictate how the tile looks[Image
(required), Title
(required), Price
(optional), SellingPrice
(required), Tags
(optional), SpecialOffers
(optional)]. Product Tile is used on the home page, search page and item page. Product Tile looks different on different pages. This is handled by conditionally rendering the children components of Product Tile.
Question: When the bundles are generated, the whole Product Tile component gets shipped for all the three pages regardless. This adversely affects the bundle size for pages which really don’t require all the features of the Product Tile to be displayed.
Approach 1 – Treat optional components like SpecialOffers
as props and pass them only when required. This would mean that it is not a part of Product Tile anymore and is displayed only when passed as a prop. The consumers decide the rendering of the optional components by passing those components as props.
Advantages
- reduce the complexity of the Product Tile component
Cons
- Eventually bloat the component with conditional rendering logic
Approach 2 – Use composition and create separate versions of the Product Tile components for the home, search and item page by using atomic children components.
Advantages
- Simpler components, easy to read and reason about
Cons
- How do we decide which new feature addition requires a new version of the Product Tile component? Should I be creating a new version of the Product Tile component for every new variant?
I am leaning towards approach 2 as that would align with React’s principles. I want to know if there are any patterns around this or any thoughts.
Thanks!