SOLID Principles in JavaScript and React
1. Single Responsibility Principle (SRP)
A class/component should have only one reason to change.
❌ Bad Example
class UserProfile {
constructor(user) {
this.user = user;
}
saveToDatabase() {
// Database logic here
}
formatUserData() {
// Data formatting logic
}
renderUserProfile() {
// UI rendering logic
}
}
✅ Good Example
// Data Service
class UserService {
saveUser(user) {
// Database logic here
}
}
// Data Formatter
class UserFormatter {
format(user) {
// Data formatting logic
}
}
// React Component
const UserProfile = ({ user }) => {
const userService = new UserService();
const userFormatter = new UserFormatter();
const handleSave = () => {
const formattedData = userFormatter.format(user);
userService.saveUser(formattedData);
};
return (
<div>
<h1>{user.name}</h1>
<button onClick={handleSave}>Save</button>
</div>
);
};
2. Open/Closed Principle (OCP)
Software entities should be open for extension but closed for modification.