DEV Community

Cover image for Interface Segregation Principle in React
Mikhael Esa
Mikhael Esa

Posted on

Interface Segregation Principle in React

I (Interface Segregation Principle)

No code should be forced to depend on methods it does not use

Taking out the trash

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.

Modular GIF



const Book = ({ book }) => {
  return (
    <div>
      <img src={book.image} alt="Book image" />
      <p>{book.title}</p>
      <p>{book.author}</p>
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

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>
  );
};


Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
souzaluiz profile image
Luiz Henrique Souza

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?

Collapse
 
pra3t0r5 profile image
Pra3t0r5

When props get too big its a signal to slice the component into smaller ones. I tend to use composite components or compound components

Collapse
 
mikhaelesa profile image
Mikhael Esa

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

// I have to go to the component to check what are the data that the Book use
<Book book={book} />

// The Book component only take title and image from the book object
<Book title={book.title} image={book.image} />
Enter fullscreen mode Exit fullscreen mode