Improve React Component Maintainability with Layered Architecture

Unlocking the Secrets to Building Scalable and Maintainable React Components

Maintainability is an essential aspect of any system. It determines how easily the system can be modified, repaired, and updated. A system will only perform optimally if all components are well maintained and software projects are no different.

If your project has a well-maintained architecture, developers can easily understand the project and make accurate changes to gain performance while shortening the development, testing, and release cycles.

The architecture of your project is a key determining factor in how easy it is to maintain the project’s components. The layered architecture is one of the best architectures for writing maintainable components for front-end frameworks such as React. Therefore, this article will discuss how to use layered architecture to write easy-to-maintain components in React and what mistakes you should avoid.

What is Layered Architecture, and Why Use It?

The layered architecture is a software design pattern that organizes an application into multiple layers or tiers, each with a specific set of responsibilities. These layers are organized hierarchically, with higher-level layers relying on lower-level layers for functionality. Most layered architectures have three or four standard layers.

Each layer can be developed and tested independently in the layered architecture, and changes to one layer do not affect the others. This separation allows developers to create organized, modular, and scalable systems that are easier to maintain and update. Furthermore, this approach allows changes to be made to the application without having to rewrite large sections of code, reducing the risk of introducing errors or breaking existing functionality.

💡 Implementing the Layered Architecture principles becomes easy with an open-source toolchain such as Bit. With Bit, your components are made independent, then versioned, tested, and shared across your project, with automatic semver and a dependency graph for each. This reduces the risk of failures caused by inconsistent dependencies or code duplication. Learn more here and here.

Build websites with independent React components and Bit:

Creating a Developer Website with Bit components

Let’s consider the 3-tier architecture as an example to see how it can improve the development experience.

The 3-Tier Architecture

As the name implies, 3-tier architecture is made up of three major layers:

  • Presentation layer
  • Business logic layer
  • Data access layer

The presentation layer manages user interactions and presents data to the user. This layer can take the form of a web interface, a desktop application, or a mobile application. It communicates with the business logic layer to execute actions and retrieve data.

The business logic layer is in charge of implementing the application’s business rules and workflows. This layer should be completely independent of the presentation layer and have no knowledge of the user interface. It should contain all the application logic and algorithms and communicate with the data access layer to retrieve the required data.

The data access layer is in charge of interacting with the application’s data sources. The layer is responsible for data retrieval and storage and should be separate from the business logic layer. It should include all code related to database access, API calls, and other external data sources.

How to use 3-Tier Architecture in React

Let’s look at how we can apply the layered architecture principle to our React applications now.

Data Access Layer

This layer is typically implemented as a set of utility functions that can be reused by various custom Hooks. Consider the following fetchData() utility function, which is used to retrieve API data.

export default async function fetchData() {
const response = fetch('https://jsonplaceholder.typicode.com/users/1').then(
(res) => {
if (res.ok) return res.json();
return Promise.reject(res);
}
);
return response;
}

This function can be used in the business logic layer whenever you need to retrieve API data without writing duplicate code. You can replace the fetch URL with a prop and modify the function as needed as the project grows. When testing API calls, you can call this function with mock data to make the process easier.

Business Logic Layer

This layer is typically implemented as a set of custom Hooks that can be reused across components. Consider the following useUserData() custom Hook, which is used to retrieve user data.

import React from "react";
import fetchData from "../util/fetchData";

const useUserData = () => {
const [userData, setUserData] = useState([]);
useEffect(() => {
fetchData()
.then((data) => setUserData(data))
.catch((res) => console.error(res.status));
}, []);
return [userData];
};

export default useUserData;

As you can see, the fetchData() function from the data access layer is called here. To make this hook more reusable, pass the URL path as a prop to the custom Hook and pass it to the fetchData() function.

Presentation Layer

The presentation layer should contain all of the UI components responsible for rendering data and responding to user actions in your React application. There should be no business logic or data-fetching code in these components.

Take a look at the UserProfile component example below.

import React from "react";
import useUserData from "./customHooks/useUserData";

const UserProfile = () => {
const [userData] = useUserData();
return (
<div>
{userData.id ? (
<div>
<ul> {userData.name} </ul>
<ul> {userData.email} </ul>
</div>
) : (
<p>Loading data...</p>
)}
</div>
);
}

export default UserProfile;

The useUserData() custom Hook is used in the component to communicate with the business logic layer and obtain user data to be displayed to the user. Apart from the return function, the only thing that should be included in UI components, as shown in this example, are function calls for the business logic layer.

This gives you clear and clean UI components, making finding and fixing UI-related bugs much easier. The repository link below will take you to the complete React layered architecture example project.

GitHub: https://github.com/Manusha17/layered-architecture-example-project

Mistakes to Avoid When Using Layered Architecture

  • Over-engineering — Maintain a simple and scalable architecture, and void using designs that do not adhere to React patterns, such as inheritance-based designs.
  • Tight coupling — When layers are tightly coupled, changing one without affecting the others can be difficult. Reduce coupling by using appropriate patterns and techniques, such as dependency injection and interfaces.
  • Ignoring performance — If not implemented correctly, layered architecture can impact application performance. Consider factors such as code splitting, lazy loading, and caching when optimizing your architecture for performance.
  • Poor naming conventions — Use clear and consistent naming conventions for your layers, components, and functions. Otherwise, it will be difficult for developers to understand and maintain the code in the long run.
  • Lack of testing — Each layer should be thoroughly tested to ensure it works as expected. Failing to test each layer can lead to bugs and other issues in the final application.
  • Lack of cohesion — Each layer has a high degree of cohesion. Cohesion refers to how closely related the functions and responsibilities within a layer are. Low cohesion can lead to code that is difficult to understand and maintain.

Conclusion

As a web development framework, React does not enforce a particular architecture. Hence, developers are responsible for selecting an appropriate architecture that promotes code maintainability in the long run. This article explores the use of layered architecture to create highly maintainable React components and what are the common mistakes we should avoid.

I hope this article will help you to build well-maintained scalable React applications using the layered architecture.

Build React Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn More


Improve React Component Maintainability with Layered Architecture was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Manusha Chethiyawardhana

Unlocking the Secrets to Building Scalable and Maintainable React Components

Maintainability is an essential aspect of any system. It determines how easily the system can be modified, repaired, and updated. A system will only perform optimally if all components are well maintained and software projects are no different.

If your project has a well-maintained architecture, developers can easily understand the project and make accurate changes to gain performance while shortening the development, testing, and release cycles.

The architecture of your project is a key determining factor in how easy it is to maintain the project’s components. The layered architecture is one of the best architectures for writing maintainable components for front-end frameworks such as React. Therefore, this article will discuss how to use layered architecture to write easy-to-maintain components in React and what mistakes you should avoid.

What is Layered Architecture, and Why Use It?

The layered architecture is a software design pattern that organizes an application into multiple layers or tiers, each with a specific set of responsibilities. These layers are organized hierarchically, with higher-level layers relying on lower-level layers for functionality. Most layered architectures have three or four standard layers.

Each layer can be developed and tested independently in the layered architecture, and changes to one layer do not affect the others. This separation allows developers to create organized, modular, and scalable systems that are easier to maintain and update. Furthermore, this approach allows changes to be made to the application without having to rewrite large sections of code, reducing the risk of introducing errors or breaking existing functionality.

💡 Implementing the Layered Architecture principles becomes easy with an open-source toolchain such as Bit. With Bit, your components are made independent, then versioned, tested, and shared across your project, with automatic semver and a dependency graph for each. This reduces the risk of failures caused by inconsistent dependencies or code duplication. Learn more here and here.

Build websites with independent React components and Bit:

Creating a Developer Website with Bit components

Let’s consider the 3-tier architecture as an example to see how it can improve the development experience.

The 3-Tier Architecture

As the name implies, 3-tier architecture is made up of three major layers:

  • Presentation layer
  • Business logic layer
  • Data access layer

The presentation layer manages user interactions and presents data to the user. This layer can take the form of a web interface, a desktop application, or a mobile application. It communicates with the business logic layer to execute actions and retrieve data.

The business logic layer is in charge of implementing the application’s business rules and workflows. This layer should be completely independent of the presentation layer and have no knowledge of the user interface. It should contain all the application logic and algorithms and communicate with the data access layer to retrieve the required data.

The data access layer is in charge of interacting with the application’s data sources. The layer is responsible for data retrieval and storage and should be separate from the business logic layer. It should include all code related to database access, API calls, and other external data sources.

How to use 3-Tier Architecture in React

Let’s look at how we can apply the layered architecture principle to our React applications now.

Data Access Layer

This layer is typically implemented as a set of utility functions that can be reused by various custom Hooks. Consider the following fetchData() utility function, which is used to retrieve API data.

export default async function fetchData() {
const response = fetch('https://jsonplaceholder.typicode.com/users/1').then(
(res) => {
if (res.ok) return res.json();
return Promise.reject(res);
}
);
return response;
}

This function can be used in the business logic layer whenever you need to retrieve API data without writing duplicate code. You can replace the fetch URL with a prop and modify the function as needed as the project grows. When testing API calls, you can call this function with mock data to make the process easier.

Business Logic Layer

This layer is typically implemented as a set of custom Hooks that can be reused across components. Consider the following useUserData() custom Hook, which is used to retrieve user data.

import React from "react";
import fetchData from "../util/fetchData";

const useUserData = () => {
const [userData, setUserData] = useState([]);
useEffect(() => {
fetchData()
.then((data) => setUserData(data))
.catch((res) => console.error(res.status));
}, []);
return [userData];
};

export default useUserData;

As you can see, the fetchData() function from the data access layer is called here. To make this hook more reusable, pass the URL path as a prop to the custom Hook and pass it to the fetchData() function.

Presentation Layer

The presentation layer should contain all of the UI components responsible for rendering data and responding to user actions in your React application. There should be no business logic or data-fetching code in these components.

Take a look at the UserProfile component example below.

import React from "react";
import useUserData from "./customHooks/useUserData";

const UserProfile = () => {
const [userData] = useUserData();
return (
<div>
{userData.id ? (
<div>
<ul> {userData.name} </ul>
<ul> {userData.email} </ul>
</div>
) : (
<p>Loading data...</p>
)}
</div>
);
}

export default UserProfile;

The useUserData() custom Hook is used in the component to communicate with the business logic layer and obtain user data to be displayed to the user. Apart from the return function, the only thing that should be included in UI components, as shown in this example, are function calls for the business logic layer.

This gives you clear and clean UI components, making finding and fixing UI-related bugs much easier. The repository link below will take you to the complete React layered architecture example project.

GitHub: https://github.com/Manusha17/layered-architecture-example-project

Mistakes to Avoid When Using Layered Architecture

  • Over-engineering — Maintain a simple and scalable architecture, and void using designs that do not adhere to React patterns, such as inheritance-based designs.
  • Tight coupling — When layers are tightly coupled, changing one without affecting the others can be difficult. Reduce coupling by using appropriate patterns and techniques, such as dependency injection and interfaces.
  • Ignoring performance — If not implemented correctly, layered architecture can impact application performance. Consider factors such as code splitting, lazy loading, and caching when optimizing your architecture for performance.
  • Poor naming conventions — Use clear and consistent naming conventions for your layers, components, and functions. Otherwise, it will be difficult for developers to understand and maintain the code in the long run.
  • Lack of testing — Each layer should be thoroughly tested to ensure it works as expected. Failing to test each layer can lead to bugs and other issues in the final application.
  • Lack of cohesion — Each layer has a high degree of cohesion. Cohesion refers to how closely related the functions and responsibilities within a layer are. Low cohesion can lead to code that is difficult to understand and maintain.

Conclusion

As a web development framework, React does not enforce a particular architecture. Hence, developers are responsible for selecting an appropriate architecture that promotes code maintainability in the long run. This article explores the use of layered architecture to create highly maintainable React components and what are the common mistakes we should avoid.

I hope this article will help you to build well-maintained scalable React applications using the layered architecture.

Build React Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

Learn More


Improve React Component Maintainability with Layered Architecture was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Manusha Chethiyawardhana


Print Share Comment Cite Upload Translate Updates
APA

Manusha Chethiyawardhana | Sciencx (2023-04-05T06:01:45+00:00) Improve React Component Maintainability with Layered Architecture. Retrieved from https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/

MLA
" » Improve React Component Maintainability with Layered Architecture." Manusha Chethiyawardhana | Sciencx - Wednesday April 5, 2023, https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/
HARVARD
Manusha Chethiyawardhana | Sciencx Wednesday April 5, 2023 » Improve React Component Maintainability with Layered Architecture., viewed ,<https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/>
VANCOUVER
Manusha Chethiyawardhana | Sciencx - » Improve React Component Maintainability with Layered Architecture. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/
CHICAGO
" » Improve React Component Maintainability with Layered Architecture." Manusha Chethiyawardhana | Sciencx - Accessed . https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/
IEEE
" » Improve React Component Maintainability with Layered Architecture." Manusha Chethiyawardhana | Sciencx [Online]. Available: https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/. [Accessed: ]
rf:citation
» Improve React Component Maintainability with Layered Architecture | Manusha Chethiyawardhana | Sciencx | https://www.scien.cx/2023/04/05/improve-react-component-maintainability-with-layered-architecture/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.