The Open-Closed Principle (OCP) is a fundamental concept in software development that ensures code is open for extension but closed for modification. In React, applying OCP leads to scalable, maintainable components that don’t require constant changes when adding new features.
✅ Definition: Software should be open for extension but closed for modification.
✅ Why It Matters:
Prevents unnecessary changes to existing code.
Improves scalability and maintainability.
Reduces complexity in large applications.
✅ Hardcoded Logic Inside Components – Components should not contain rigid logic that requires modification for every new feature.
✅ Modifying Components for Every Update – Instead of altering components, extend them using props or external configurations.
✅ Increased Complexity Over Time – Each modification makes components harder to read, test, and maintain.
✅ Use Composition Over Modification – Extend components via props instead of changing their logic.
✅ Create Base Components – Design reusable components that can be extended.
✅ Leverage Custom Hooks – Separate concerns for better maintainability.
✅ Utilize Theme Configurations – Manage styles externally to avoid modifying core components.
Instead of modifying a button component for every new variant, use theme-based styling:
✅ Before (Violating OCP):
const Button = ({ variant, ...restProps }) => {
let classes = "border rounded-md";
if (variant === "primary") {
classes += " bg-primary text-white";
} else if (variant === "secondary") {
classes += " bg-secondary text-white";
}
return <button className={classes} {...restProps} />;
};
✅ After (Following OCP):
const Button = ({ variant, ...restProps }) => {
const { theme: { button: theme } } = useTheme();
const classes = theme.variant[variant];
return <button className={classes} {...restProps} />;
};
Now, new variants can be added without modifying the component, making it easier to test, read, and maintain.
Applying the Open-Closed Principle in React leads to scalable, maintainable components that adapt to new requirements without unnecessary modifications.
🔥 Have you applied OCP in your React projects? Let’s discuss! 🚀
Join Shikhil on Peerlist!
Join amazing folks like Shikhil and thousands of other people in tech.
Create ProfileJoin with Shikhil’s personal invite link.
0
7
0