I (Interface Segregation Principle)
No code should be forced to depend on methods it does not use
In React, the Interface Segregation Principle (ISP) emphasizes the importance of creating precise and minimal interfaces for components. It encourages developers to design component interfaces that are tailored to specific needs, avoiding unnecessary bloat.
This approach results in more modular, maintainable, and reusable code, as components become smaller and focused, promoting better readability and scalability in React applications. ISP encourages cleaner, efficient codebases by advocating for lean and specialized component interfaces.
const Book = ({ book }) => {
return (
<div>
<img src={book.image} alt="Book image" />
<p>{book.title}</p>
<p>{book.author}</p>
</div>
);
};
We have a book component which only need few data from the book props which are image, title, and author. By giving it book as a props, we end up giving it more than the component actually need because the book props itself might contain data that the component doesn't need
To mitigate this problem we can limit the props to only what the component need.
const Book = ({ image, title, author }) => {
return (
<div>
<img src={image} alt="Book image" />
<p>{title}</p>
<p>{author}</p>
</div>
);
};
By doing so, we are applying the ISP principle, thus avoiding clients of our component from depending on an interface they are not using.
What's next?
Let's not stop here since there is 1 principle left to learn in SOLID which I will cover in the next article so stay tuned.
Dadah~ 👋
Top comments (3)
What would be the ideal limit to do this? If I'm going to use several items from this object, wouldn't it be better to continue passing the object?
When props get too big its a signal to slice the component into smaller ones. I tend to use composite components or compound components
Ideally if I know what data I'm going to pass to the component, I would just do this instead of passing the whole book data. This approach also help me to have a clue of the data that the component use.
One code sample here