Open-Closed Principle in React: Building Extensible Components
Introduction
After exploring Dependency Inversion, Interface Segregation, and Liskov Substitution, let’s tackle the Open-Closed Principle (OCP) in the context of modern React applications.
Again, kudos to Uncle Bob for reminding me about the importance of good software architecture in his classic Clean Architecture! That book is my primary inspiration for this series.
The Open-Closed Principle states that software entities should be open for extension but closed for modification.
In React terms: components should be easy to extend without changing their existing code. Let’s see how this plays out in practice.
The Problem with Closed Components
Here’s a common anti-pattern:
1// DON'T DO THIS
2const Button = ({ label, onClick, variant }: ButtonProps) => {
3 let className = "button";
4
5 // Direct modification for each variant
6 if (variant === "primary") {
7 className += " button-primary";
8 } else if (variant === "secondary") {
9 className += " button-secondary";
10 } else if (variant === "danger") {
11 className += " button-danger";
12 }
13
14 return (
15 <button className={className} onClick={onClick}>
16 {label}
17 </button>
18 );
19};
This violates OCP because:
- Adding a new variant requires modifying the component
- The component needs to know about all possible variants
- Testing becomes more complex with each addition
Building Open Components
Let’s refactor this to follow OCP:
1type ButtonBaseProps = {
2 label: string;
3 onClick: () => void;
4 className?: string;
5 children?: React.ReactNode;
6};
7
8const ButtonBase = ({
9 label,
10 onClick,
11 className = "",
12 children,
13}: ButtonBaseProps) => (
14 <button className={`button ${className}`.trim()} onClick={onClick}>
15 {children || label}
16 </button>
17);
18
19// Variant components extend the base
20const PrimaryButton = (props: ButtonBaseProps) => (
21 <ButtonBase {...props} className="button-primary" />
22);
23
24const SecondaryButton = (props: ButtonBaseProps) => (
25 <ButtonBase {...props} className="button-secondary" />
26);
27
28const DangerButton = (props: ButtonBaseProps) => (
29 <ButtonBase {...props} className="button-danger" />
30);
Now we can easily add new variants without modifying existing code:
1// Adding a new variant without touching the original components
2const OutlineButton = (props: ButtonBaseProps) => (
3 <ButtonBase {...props} className="button-outline" />
4);
Component Composition Pattern
Let’s look at a more complex example using composition:
1type CardProps = {
2 title: string;
3 children: React.ReactNode;
4 renderHeader?: (title: string) => React.ReactNode;
5 renderFooter?: () => React.ReactNode;
6 className?: string;
7};
8
9const Card = ({
10 title,
11 children,
12 renderHeader,
13 renderFooter,
14 className = "",
15}: CardProps) => (
16 <div className={`card ${className}`.trim()}>
17 {renderHeader ? (
18 renderHeader(title)
19 ) : (
20 <div className="card-header">{title}</div>
21 )}
22
23 <div className="card-content">{children}</div>
24
25 {renderFooter && renderFooter()}
26 </div>
27);
28
29// Extended without modification
30const ProductCard = ({ product, onAddToCart, ...props }: ProductCardProps) => (
31 <Card
32 {...props}
33 renderFooter={() => (
34 <button onClick={onAddToCart}>Add to Cart - ${product.price}</button>
35 )}
36 />
37);
Higher-Order Components for Extension
HOCs provide another way to follow OCP:
1type WithLoadingProps = {
2 isLoading?: boolean;
3};
4
5const withLoading = <P extends object>(
6 WrappedComponent: React.ComponentType<P>
7) => {
8 return ({ isLoading, ...props }: P & WithLoadingProps) => {
9 if (isLoading) {
10 return <div className="loader">Loading...</div>;
11 }
12
13 return <WrappedComponent {...(props as P)} />;
14 };
15};
16
17// Usage
18const UserProfileWithLoading = withLoading(UserProfile);
Custom Hooks Following OCP
Custom hooks can also follow OCP:
1const useDataFetching = <T,>(url: string) => {
2 const [data, setData] = useState<T | null>(null);
3 const [error, setError] = useState<Error | null>(null);
4 const [loading, setLoading] = useState(true);
5
6 useEffect(() => {
7 fetchData();
8 }, [url]);
9
10 const fetchData = async () => {
11 try {
12 const response = await fetch(url);
13 const result = await response.json();
14 setData(result);
15 } catch (e) {
16 setError(e as Error);
17 } finally {
18 setLoading(false);
19 }
20 };
21
22 return { data, error, loading, refetch: fetchData };
23};
24
25// Extended without modification
26const useUserData = (userId: string) => {
27 const result = useDataFetching<User>(`/api/users/${userId}`);
28
29 // Add user-specific functionality
30 const updateUser = async (data: Partial<User>) => {
31 // Update logic
32 };
33
34 return { ...result, updateUser };
35};
Testing Benefits
OCP makes testing much more straightforward:
1describe("ButtonBase", () => {
2 it("renders with custom className", () => {
3 render(<ButtonBase label="Test" onClick={() => {}} className="custom" />);
4
5 expect(screen.getByRole("button")).toHaveClass("button custom");
6 });
7});
8
9// New variants can have their own tests
10describe("PrimaryButton", () => {
11 it("includes primary styling", () => {
12 render(<PrimaryButton label="Test" onClick={() => {}} />);
13
14 expect(screen.getByRole("button")).toHaveClass("button button-primary");
15 });
16});
Key Takeaways
- Use composition over modification - extend through props and render props
- Create base components that are easy to extend
- Leverage HOCs and custom hooks for reusable extensions
- Think in terms of extension points - what might need to change?
- Use TypeScript to make extensions type-safe
OCP and “Composition over Inheritance”
The React team’s recommendation of “composition over inheritance” aligns perfectly with the Open-Closed Principle. Here’s why:
1// Inheritance-based approach (less flexible)
2class Button extends BaseButton {
3 render() {
4 return (
5 <button className={this.getButtonClass()}>
6 {this.props.icon && <Icon name={this.props.icon} />}
7 {this.props.label}
8 </button>
9 );
10 }
11}
12
13// Composition-based approach (more flexible, follows OCP)
14const Button = ({
15 label,
16 icon,
17 renderPrefix,
18 renderSuffix,
19 ...props
20}: ButtonProps) => (
21 <ButtonBase {...props}>
22 {renderPrefix?.()}
23 {icon && <Icon name={icon} />}
24 {label}
25 {renderSuffix?.()}
26 </ButtonBase>
27);
28
29// Now we can extend behavior without modification
30const DropdownButton = ({ items, ...props }: DropdownButtonProps) => (
31 <Button
32 {...props}
33 renderSuffix={() => <DropdownIcon />}
34 onClick={() => setIsOpen(true)}
35 />
36);
37
38const LoadingButton = ({ isLoading, ...props }: LoadingButtonProps) => (
39 <Button
40 {...props}
41 renderPrefix={() => isLoading && <Spinner />}
42 disabled={isLoading}
43 />
44);
This composition-based approach:
- Makes components open for extension (through props and render functions)
- Keeps base components closed for modification
- Allows for unlimited combinations of behaviors
- Maintains type safety and prop transparency
The React team’s preference for composition isn’t just about style—it’s about creating extensible, maintainable components that naturally follow OCP.
Conclusion
The Open-Closed Principle might seem abstract, but in React it translates to practical patterns that make our components more maintainable and flexible. Combined with our previous SOLID principles, it helps create a robust architecture that’s easy to extend and maintain.
Stay tuned for our final post in the series, where we’ll explore the Single Responsibility Principle!
Pro tip: If you find yourself using lots of if/else statements for different variants or behaviors, you’re probably violating OCP. Consider using composition instead.
Update: Friendly Disclaimer and Reminder
If you’re looking for a comprehensive guide to software architecture, this is not it. The purpose of my recent posts about software architecture is to explore some some principles in a practical way, principles I’ve previously been too quick to dismiss or too lazy to apply. I’m neither claiming mastery of these concepts, nor am I suggesting that these principles should be rigidly applied in every situation. I’m not even proposing that my brief examples are the best way to implement or even explain these principles. Rather, I’m documenting my attempts to bridge classical software engineering principles with contemporary development practices. In fact, I have yet to decide for my self how close to “Clean Architecture” I want to get in the end vs how pragmatic I want to be. But for now I’m (mostly) enjoying the learning and exploration. Keep that in mind before you harass me, Uncle Bob or anyone else on Reddit about it 😅
And to all of you who have disagreed with me in a meaningful and respectful way, thank you. It’s been a great learning experience for me.
Thanks :)