Single Responsibility Principle
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users", { method: "GET" })
.then((response) => response.json())
.then(setUsers);
}, []);
return (
<section>
<h1>Users: </h1>
<ul>
{users.map((user) => (
<li>{user.username}</li>
))}
</ul>
</section>
);
}
function Users({ users }) {
return (
<section>
<h1>Users: </h1>
<ul>
{users.map((user) => (
<li key={`user-${user.username}`}>{user.username}</li>
))}
</ul>
</section>
);
}
function UsersContainer() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users", { method: "GET" })
.then((response) => response.json())
.then(setUsers);
}, []);
return <Users users={users} />;
}
You should be able to add functionality to some module, without modifying its existing source code
function UsersContainer() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users", { method: "GET" })
.then((response) => response.json())
.then(setUsers);
}, []);
return <Users users={users} />;
}
function Users({ users }) {
return (
<section>
<h1>Users: </h1>
<ul>
{users.map((user) => (
<User user={user} />
))}
</ul>
</section>
);
}
function User({ user }) {
return (
<article key={`user-${user.username}`} className="user">
<span>{user.username}</span>
<div className="user__contact-info">
{user.company.name}
{user.email}
</div>
</article>
);
}
Substitution Principle (Liskov)
function Users({ users }) {
return (
<section>
<h1>Users: </h1>
<ul>
{users.map((user) => (
- <User user={user} />
+ <UserCard user={user} />
))}
</ul>
</section>
);
}
Interface Segregation Principle
-function UserCard({ user }) {
+function UserCard({ username, company, email }) {
Dependency Inversion Principle
function useUsers() {
const [users, setUsers] = useState([]);
useEffect(() => {
let isSubscribed = true;
api.fetchUsers().then((users) => {
if (isSubscribed) {
setUsers(users);
}
});
const cleanUp = () => {
isSubscribed = false;
};
return cleanUp;
}, []);
return { users };
}
function UsersContainer() {
const { users } = useUsers();
return <Users users={users} />;
}
function UsersContainer() {
const { users } = useUsers();
return <Users users={users} />;
}