Home Web Front-end JS Tutorial SOLID Principles in React: The Key to Writing Maintainable Components

SOLID Principles in React: The Key to Writing Maintainable Components

Sep 29, 2024 am 06:19 AM

SOLID Principles in React: The Key to Writing Maintainable Components

As React applications grow, things can get messy fast—bloated components, hard-to-maintain code, and unexpected bugs. That’s where the SOLID principles come in handy. Originally developed for object-oriented programming, these principles help you write clean, flexible, and scalable code. In this article, I’ll break down each SOLID principle and show how you can use them in React to keep your components organized, your code easier to maintain, and your app ready to grow.

SOLID is an acronym that stands for five design principles aimed at writing clean, maintainable, and scalable code, originally for object-oriented programming but also applicable in React:

S: Single Responsibility Principle: Components should have one job or responsibility.

O: Open/Closed Principle: components should be open for extension **(easily enhanced or customized) but **closed for modification (their core code shouldn't need changes).

L: Liskov Substitution Principle: components should be replaceable by their child components without breaking the app's behavior.

I: Interface Segregation Principle: Components should not be forced to depend on unused functionality.

D: Dependency Inversion Principle: Components should depend on abstractions, not concrete implementations.

Single Responsibility Principle (SRP)

Think of it like this: Imagine you have a toy robot that can only do one job, like walking. If you ask it to do a second thing, like talk, it gets confused because it's supposed to focus on walking! If you want another job, get a second robot.

In React, a component should only do one thing. If it does too much, like fetching data, handling form inputs, and showing UI all at once, it gets messy and hard to manage.

const UserCard = () => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetch('/api/user')
      .then(response => response.json())
      .then(data => setUser(data));
  }, []);

  return user ? ( <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div> ) : <p>Loading...</p>;
};
Copy after login

Here, the UserCard is responsible for both fetching data and rendering the UI, which breaks the Single Responsibility Principle.

const useFetchUser = (fetchUser) => {
  const [user, setUser] = useState(null);

  useEffect(() => {
    fetchUser().then(setUser);
  }, [fetchUser]);

  return user;
};

const UserCard = ({ fetchUser }) => {
  const user = useFetchUser(fetchUser);

  return user ? (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  ) : (
    <p>Loading...</p>
  );
};

Copy after login

Here, the data fetching logic is moved to a custom hook (useFetchUser), while UserCard focuses solely on rendering the UI, and maintaining SRP.

Open/Closed Principle (OCP)

Think of a video game character. You can add new skills to the character (extensions) without changing their core abilities (modifications). That’s what OCP is about—allowing your code to grow and adapt without altering what’s already there.

const Alert = ({ type, message }) => {
  if (type === 'success') {
    return <div className="alert-success">{message}</div>;
  }
  if (type === 'error') {
    return <div className="alert-error">{message}</div>;
  }
  return <div>{message}</div>;
};
Copy after login

Here, every time you need a new alert type, you have to modify the Alert component, which breaks OCP. whenever you add conditional rendering or switch case rendering in your component, you are making that component less maintainable, cause you have to add more conditions in the feature and modify that component core code that breaks OCP.

const Alert = ({ className, message }) => (
  <div className={className}>{message}</div>
);

const SuccessAlert = ({ message }) => (
  <Alert className="alert-success" message={message} />
);

const ErrorAlert = ({ message }) => (
  <Alert className="alert-error" message={message} />
);
Copy after login

Now, the Alert component is open for extension (by adding SuccessAlert, ErrorAlert, etc.) but closed for modification because we don’t need to touch the core Alert component to add new alert types.

Want OCP? Prefer composition to inheritance

Liskov Substitution Principle (LSP)

Imagine you have a phone, and then you get a new smartphone. You expect to make calls on the smartphone just like you did with the regular phone. If the smartphone couldn’t make calls, it would be a bad replacement, right? That's what LSP is about—new or child components should work just like the original without breaking things.

const Button = ({ onClick, children }) => (
  <button onClick={onClick}>{children}</button>
);

const IconButton = ({ onClick, icon }) => (
  <Button onClick={onClick}>
    <i className={icon} />
  </Button>
);
Copy after login

Here, if you swap the Button with the IconButton, you lose the label, breaking the behavior and expectations.

const Button = ({ onClick, children }) => (
  <button onClick={onClick}>{children}</button>
);

const IconButton = ({ onClick, icon, label }) => (
  <Button onClick={onClick}>
    <i className={icon} /> {label}
  </Button>
);

// IconButton now behaves like Button, supporting both icon and label

Copy after login

Now, IconButton properly extends Button's behavior, supporting both icons and labels, so you can swap them without breaking functionality. This follows the Liskov Substitution Principle because the child (IconButton) can replace the parent (Button) without any surprises!

If B component extends A component, anywhere you use A component, you should be able to use B component.

Interface Segregation Principle (ISP)

Imagine you’re using a remote control to watch TV. You only need a few buttons like power, volume, and channel. If the remote had tons of unnecessary buttons for a DVD player, radio, and lights, it would be annoying to use.

Suppose you have a data table component that takes a lot of props, even if the component using it doesn’t need all of them.

const DataTable = ({ data, sortable, filterable, exportable }) => (
  <div>
    {/* Table rendering */}
    {sortable && <button>Sort</button>}
    {filterable && <input placeholder="Filter" />}
    {exportable && <button>Export</button>}
  </div>
);
Copy after login

This component forces all consumers to think about sorting, filtering, and exporting—even if they only want a simple table.

You can split the functionality into smaller components based on what’s needed.

const DataTable = ({ data }) => (
  <div>
    {/* Table rendering */}
  </div>
);

const SortableTable = ({ data }) => (
  <div>
    <DataTable data={data} />
    <button>Sort</button>
  </div>
);

const FilterableTable = ({ data }) => (
  <div>
    <DataTable data={data} />
    <input placeholder="Filter" />
  </div>
);
Copy after login

Now, each table only includes the functionality that’s needed, and you’re not forcing unnecessary props everywhere. This follows ISP, where components only depend on the parts they need.

Dependency Inversion Principle (DIP)

Imagine you're building with LEGO blocks. You have a robot built with specific pieces. But what if you want to swap out its arms or legs? You shouldn't have to rebuild the whole thing—just swap out the parts. The Dependency Inversion Principle (DIP) is like this: your robot (high-level) doesn't depend on specific parts (low-level); it depends on pieces that you can change easily.

const UserComponent = () => {
  useEffect(() => {
    fetch('/api/user').then(...);
  }, []);
  return <div>...</div>;
};
Copy after login

This directly depends on fetch—you can’t swap it easily.

const UserComponent = ({ fetchUser }) => {
  useEffect(() => {
    fetchUser().then(...);
  }, [fetchUser]);
  return <div>...</div>;
};
Copy after login

Now, the fetchUser function is passed in, and you can easily swap it with another implementation (e.g., mock API, or another data source), keeping everything flexible and testable.

Final Thoughts

Understanding and applying SOLID principles in React can drastically improve the quality of your code. These principles—Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion—help you write components that are more modular, flexible, and easier to maintain. By breaking down responsibilities, keeping code extensible, and making sure each part of your app interacts in predictable ways, you can create React applications that scale more easily and are simpler to debug. In short, SOLID principles lead to cleaner and more maintainable codebases.

The above is the detailed content of SOLID Principles in React: The Key to Writing Maintainable Components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles