Interface Segregation Principle (ISP)

Interface Segregation Principle (ISP)

REACT NATIVE HUB
  • Definition: Clients should not be forced to depend on interfaces they do not use.
  • In React: Ensure that components accept only the props they need, and use custom hooks to separate different concerns.

Not following ISP: In this example, the extended interface is forced to implement all props even if it doesn’t need them.

// ❌ BAD EXAMPLE - Violating ISP
interface ButtonProps {
  label: string;
  onClick: () => void;
  icon: string;        // Not all buttons need icons
  loading: boolean;    // Not all buttons need loading state
  disabled: boolean;   // Not all buttons need disabled state
}

const Button: React.FC<ButtonProps> = ({ label, onClick, icon, loading, disabled }) => {
  return (
    <button onClick={onClick} disabled={disabled}>
      {loading ? "Loading..." : label}
      {icon && <span>{icon}</span>}
    </button>
  );
};

Following ISP: Now, let’s refactor this code by Segregating interfaces for different aspects of the button.

// ✅ GOOD EXAMPLE - Following ISP
interface BasicButtonProps {
  label: string;
  onClick: () => void;
}

interface LoadingButtonProps extends BasicButtonProps {
  loading: boolean;
}

// Simple button without unnecessary props
const SimpleButton: React.FC<BasicButtonProps> = ({ label, onClick }) => {
  return <button onClick={onClick}>{label}</button>;
};

// Button with loading state
const LoadingButton: React.FC<LoadingButtonProps> = ({ label, onClick, loading }) => {
  return (
    <button onClick={onClick}>
      {loading ? "Loading..." : label}
    </button>
  );
};




Report Page