We collided two different approaches how write React components:
1st approach: create different components for different use cases
export default function HeaderForEdit(): ReactNode {
return (
<div className="class1 class2 class3">
<Button icon={back} title={"Go back"} />
<div>
<Title>Edit</Title>
<Subtitle>You can edit this file</Subtitle>
</div>
</div>
);
}
export default function HeaderForCreate(): ReactNode {
return (
<div className="class1 class3">
<div>
<Title>Create</Title>
</div>
</div>
);
}
The second approach says this is very similar, so merge into one component, add some properties to support conditional rendering:
export default function HeaderForAnything({ icon, icontTitle, title, subtitle }): ReactNode {
return (
<div className={icon ? "class1 class2 class3" : "class1 class3"}>
{icon && <Button icon={icon} title={iconTitle} />}
<div>
<Title>{title}</Title>
{subTitle && <Subtitle>You can edit this file</Subtitle>}
</div>
</div>
);
}
With the proper parameterization this one component could do both.
The pro-s for the 2nd approach are:
- less components, smaller size of the final bundle
- it is how react works, its reusable component, can fit for both cases
- more maintainable, as we should maintain only one component not two
I don’t really know too much about the 1st pro, about the bundle size, but don’t see the 2nd and 3rd option at all. Its of course reusable as it is (in a braver moment we can call it as a “generic” component) – but if we have a 3rd use case, we should add more properties to fit that use case. Also is not readable for me as don’t recognize as the icon
option controls exactly what inside this component, for example I don’t add an icon but want to use a subTitle
– it cannot. If we modify this component that not the icon but something else controls if the subTitle is rendered or not – its very dangerous for me as should view all the places it is used to discover if it spoils that usage or not.
The 1st approach is much more simpler for me, if we use atomic pattern
there are simple reusable components, several, and we combine them into a bigger component, importing only those components which are needed. In this approach almost no extra property is needed because no conditional rendering is used. Also seems much more maintainable, because a component is used in few places only, less chance to spoil a code somewhere else, etc.
But I cannot handle the reasoning that “this is how react works”. So now I’m here: what are the practices and recommendations how to do it in a larger project nowadays?