DEV Community

Cover image for ReactJS SOLID Principle ~ISP (Interface Segregation Principle)~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS SOLID Principle ~ISP (Interface Segregation Principle)~

In React, the interface(props defined as TypeScript) should have only types that are used in the component.

For example:

import React, { VFC } from "react";

type PostType = {
  title: string;
  author: {
    name: string;
    age: number;
  };
  createdAt: Date;
};

export const Post = ({ post }: { post: PostType }) => {
  return (
    <div>
      <PostTitle post={post} />
      <span>author: {post.author.name}</span>
      <PostDate post={post} />
    </div>
  );
};

type Props = {
  post: PostType;
};

export const PostTitle: VFC<Props> = ({ post }) => {
  return <h1>{post.title}</h1>;
};

type DateProps = {
  post: PostType;
};

export const PostDate: VFC<DateProps> = ({ post }) => {
  return <time>{post.createdAt}</time>;
};
Enter fullscreen mode Exit fullscreen mode

The Post component has the Posttitle component and the PostDate component.
One shows title, the other shows post date.

This breaks the ISP.

The Posttitle component depends on the post: PostType property. But this component actually uses the name property. This means that the Posttitle depends on the unnecessary interface.

If the post: PostType is modified, this has an effect on the PostTitle component and PostDate component.

ISP is also related to SRP and OCP; if interfaces are not properly separated, a component may end up having more than one responsibility, leaving it vulnerable to changes during extension.

Therefore, this issue can be resolved by defining only the necessary interfaces, as shown below.

import React, { VFC } from "react";

type PostType = {
  title: string;
  author: {
    name: string;
    age: number;
  };
  createdAt: Date;
};

export const Post = ({ post }: { post: PostType }) => {
  return (
    <div>
      <PostTitle title={post.title} />
      <span>author: {post.author.name}</span>
      <PostDate date={post.createdAt} />
    </div>
  );
};

type Props = {
  title: string;
};

export const PostTitle: VFC<Props> = ({ title }) => {
  return <h1>{title}</h1>;
};

type DateProps = {
  date: Date
};

export const PostDate: VFC<DateProps> = ({ date }) => {
  return <time>{date}</time>;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)