Moving away from ReactJs and VueJs on front-end using Clean Architecture
Jorge Sánchez Fernández
Posted on July 12, 2021
This article is an English translation of the original in my blog: Alejándonos de ReactJs y VueJs en el front end usando Clean Architecture.
One of the advantages of using Clean Architecture, among others, is the ability to uncouple our application of the delivery mechanism to the user, that is, from the UI framework or library.
This advantage in long-term applications allows us to adapt in the future to the changes that will surely take place in libraries and frameworks.
In this article, we will take Clean Architecture to the extreme in the front-end by applying two delivery mechanisms: ReactJS and VueJs.
We will have as much code as possible reused between the two implementations.
This will be possible by creating the domain, data, and remote display logic of ReactJs and VueJs.
Why move away from the framework?
I have developed different technologies applying Clean Architecture like .Net, Android, iOS, and Flutter. For a long time, I am also programming in the front-end and writing about it.
One of the biggest problems when it comes to evolving an application is the coupling to the UI framework.
On the front-end little by little due to the responsibilities that applications of this type have been gained over time, it makes more and more sense to develop in a more structured way and the problems to be solved are very similar to those that exist on other fronts such as backend or mobile development.
There are frameworks like ReactJs and VueJs that make life easier for us to take on these challenges on the front-end.
A front-end application today is an independent application of the backend in many cases and therefore needs to have its own architecture.
In addition, this architecture must help us in the next points:
- Independent of UI, frameworks, API rest and persistence, databases o third-party services.
- Escalability.
- Testability.
This means that if we change the vision of having a ReactJs or VueJs application, to have a front-end application that uses ReactJs or VueJs to render, this will make our lives much easier in the future.
So, for example, evolving your ReactJS application from using classes as before, to using functions and hooks as is done now, is much more trivial. The same happens if you switch in VueJS from using the options API to the composition API.
It’s more trivial because you only use the framework for what is strictly necessary, such as rendering and thus you do not overuse it, keeping it away from any type of logic, be its domain, data, or presentation logic.
Frameworks evolve and you cannot control that, but what you can control is the coupling you have with them and how their changes affect you.
But in this case, we are going to go beyond how to adapt to changes that can happen in a framework and we are going to see the amount of code that could not change when we modify ReactJS by VueJS if we use Clean Architecture and separate responsibilities.
This is the picture you keep in mind if you develop using Clean Architecture.
If you don’t have clear the concepts of Clean Architecture, I recommend that you read this article.
The most important part is the dependency rule, so if you don’t know what I’m talking about, I recommend that you read this article.
The example that we are going to see is based on the one we saw in this article.
Our scenario
It’s a shopping cart with enough functionality to look like a real example. We are going to have a global state, non-global state, and we will simulate invoke to a remote service.
Architecture
At the project structure level, we will use a monorepo using yarn workspaces, in this way we can split the project into modules or packages sharing code between them.
We have several packages:
- Core: in this package, we will have all the shared code between the app rendered by ReactJS and the app rendered by VueJs.
- React: in this package is found the react app version.
- Vue: in this package is found the Vue app version.
¿What code is reused?
We are going to reuse all the code that we must have uncoupled from the UI Framework, since being different versions of the same app it makes sense that this code is shared and not write twice.
This is a demonstration exercise of the potential that Clean Architecture has but this uncoupling of the UI framework is necessary even when we develop a real app.
Using the UI framework for what is strictly necessary allows us to better adapt to changes in future versions of the framework.
This is because the code that contains the application logic, which is the most important part, that changes less over time, and is the code potentially to be shared between two versions of the same app as in this example, it’s uncoupled without depending on the UI framework.
In Clean Architecture the domain layer is where the enterprise and application business logic is located.
The data layer is where we communicate with the persistence.
The presentation logic is the one that decides what data is shown if something should be visible or not if it should be shown to the user that we are loading data or if an error should be displayed. It is where the state of the components is managed.
Each of these 3 parts contains logic that we must uncouple and is found in the core package.
Domain Layer
The domain layer is where the enterprise and application business logic is located.
Use Cases
Use cases are intents, contains the business logic of the application, they are actions and in this example, we have the next:
- GetProductsUseCase
- GetCartUseCase
- AddProductToCartUseCase
- EditQuantityOfCartItemUseCase
- RemoveItemFromCartUseCase
Let’s see the example of GetProductsUseCase:
export class GetProductsUseCase {
private productRepository: ProductRepository;
constructor(productRepository: ProductRepository) {
this.productRepository = productRepository;
}
execute(filter: string): Promise<Either<DataError, Product[]>> {
return this.productRepository.get(filter);
}
}
This use case is simple because it consists of a simple call to the data layer, in other contexts where, for example, when creating a product, we have to validate that there is no longer one with the same SKU, there would be more logic.
The use cases returns Either type, if you are not sure what it is then I recommend that you read this article and this article.
In this way, the error handling is not done using the catch of the promises, but the result object of the promise itself tells you if the result is successful or not.
The use of Either versus the classic try-catch has several advantages:
- The flow of execution is simpler to follow without jumps between callers when an error occurs.
- That something can go wrong, is explicitly indicated. Errors that may occur are explicitly indicated.
- Doing the use of the exhaustive switch, if you add more errors in the future, TypeScript will warn you where you have not taken this new error into account.
The type for the errors is as follows:
export interface UnexpectedError {
kind: "UnexpectedError";
message: Error;
}
export type DataError = UnexpectedError;
Potentially in the future, it could evolve to something like this:
export interface ApiError {
kind: "ApiError";
error: string;
statusCode: number;
message: string;
}
export interface UnexpectedError {
kind: "UnexpectedError";
message: Error;
}
export interface Unauthorized {
kind: "Unauthorized";
}
export interface NotFound {
kind: "NotFound";
}
export type DataError = ApiError | UnexpectedError | Unauthorized;
And in the presentation layer, if I’m using an exhaustive switch, Typescript would warn me, I should add more cases for each new error.
Entities
The entities contain the enterprise business logic.
Let’s see the example of Cart:
type TotalPrice = number;
type TotalItems = number;
export class Cart {
items: readonly CartItem[];
readonly totalPrice: TotalPrice;
readonly totalItems: TotalItems;
constructor(items: CartItem[]) {
this.items = items;
this.totalPrice = this.calculateTotalPrice(items);
this.totalItems = this.calculateTotalItems(items);
}
static createEmpty(): Cart {
return new Cart([]);
}
addItem(item: CartItem): Cart {
const existedItem = this.items.find(i => i.id === item.id);
if (existedItem) {
const newItems = this.items.map(oldItem => {
if (oldItem.id === item.id) {
return { ...oldItem, quantity: oldItem.quantity + item.quantity };
} else {
return oldItem;
}
});
return new Cart(newItems);
} else {
const newItems = [...this.items, item];
return new Cart(newItems);
}
}
removeItem(itemId: string): Cart {
const newItems = this.items.filter(i => i.id !== itemId);
return new Cart(newItems);
}
editItem(itemId: string, quantity: number): Cart {
const newItems = this.items.map(oldItem => {
if (oldItem.id === itemId) {
return { ...oldItem, quantity: quantity };
} else {
return oldItem;
}
});
return new Cart(newItems);
}
private calculateTotalPrice(items: CartItem[]): TotalPrice {
return +items
.reduce((accumulator, item) => accumulator + item.quantity * item.price, 0)
.toFixed(2);
}
private calculateTotalItems(items: CartItem[]): TotalItems {
return +items.reduce((accumulator, item) => accumulator + item.quantity, 0);
}
}
In this example, the entities are simple, with properties of primitive types, but a real example where there were validations we could have Entities and Value Objects defined as classes and with factory methods where the validation is performed. We use Either to return the errors or the result.
Boundaries
The boundaries are the abstractions of the adapters, for example, in Hexagonal Architecture they are called ports. They are defined in the layer of the use cases in the domain and indicate how we are going to communicate with the adapters.
For example, to communicate with the data layer we use the repository pattern.
export interface ProductRepository {
get(filter: string): Promise<Either<DataError, Product[]>>;
}
Data Layer
The data layer is where the adapters are found and an adapter is responsible to transform the information between the domain and external systems.
External systems may be a web service, a database, etc…
In this simple example, I’m using the same entities that represent the product, shopping cart, and cart items between the presentation, domain, and data layers.
In real applications, is common to have a different data structure for each layer or even to have Data Transfer Objects (DTOs) to pass data between layers.
In this example, we have repositories that return data stored in memory.
const products = [
...
];
export class ProductInMemoryRepository implements ProductRepository {
get(filter: string): Promise<Either<DataError, Product[]>> {
return new Promise((resolve, _reject) => {
setTimeout(() => {
try {
if (filter) {
const filteredProducts = products.filter((p: Product) => {
return p.title.toLowerCase().includes(filter.toLowerCase());
});
resolve(Either.right(filteredProducts));
} else {
resolve(Either.right(products));
}
} catch (error) {
resolve(Either.left(error));
}
}, 100);
});
}
}
The important thing is to understand that the repository is an adapter and that its abstraction or port is defined in the domain, so the traditional direction of the dependency is inverted.
This is the most important part of Clean Architecture, the domain should not have any dependency on external layers, in this way it is uncoupled and it will be easier to replace an adapter with another in the future or even for testing purposes.
In this way, if we replace the adapter implementation with one that invokes a web service, the domain is not affected and therefore we are hiding implementation details.
Presentation Layer — Adapters
The adapters of the presentation layer are the last reuse part of our core package and It’s where we hook the UI React or Vue layers.
These adapters are also reusable between the two versions of the app, they are intermediaries between the UI components and the domain layer.
They contain the presentation logic, deciding what information is shown, what should be visible, etc…
The state management is performed by this layer and does not depend on React or Vue.
There are different presentation patterns that we can use. In this case, I am using the BLoC Pattern because it fits very well with declarative frameworks such as React and Vue.
If you want to delve into the BLoC pattern, I recommend that you read this article.
As I discussed in that article, when you use BLoC with Clean Architecture, it makes more sense to call them PLoC, Presentation Logic Component. So in this example, they are named this way.
Let’s see the shopping cart example:
export class CartPloc extends Ploc<CartState> {
constructor(
private getCartUseCase: GetCartUseCase,
private addProductToCartUseCase: AddProductToCartUseCase,
private removeItemFromCartUseCase: RemoveItemFromCartUseCase,
private editQuantityOfCartItemUseCase: EditQuantityOfCartItemUseCase
) {
super(cartInitialState);
this.loadCart();
}
closeCart() {
this.changeState({ ...this.state, open: false });
}
openCart() {
this.changeState({ ...this.state, open: true });
}
removeCartItem(item: CartItemState) {
this.removeItemFromCartUseCase
.execute(item.id)
.then(cart => this.changeState(this.mapToUpdatedState(cart)));
}
editQuantityCartItem(item: CartItemState, quantity: number) {
this.editQuantityOfCartItemUseCase
.execute(item.id, quantity)
.then(cart => this.changeState(this.mapToUpdatedState(cart)));
}
addProductToCart(product: Product) {
this.addProductToCartUseCase
.execute(product)
.then(cart => this.changeState(this.mapToUpdatedState(cart)));
}
private loadCart() {
this.getCartUseCase
.execute()
.then(cart => this.changeState(this.mapToUpdatedState(cart)))
.catch(() =>
this.changeState({
kind: "ErrorCartState",
error: "An error has ocurred loading products",
open: this.state.open,
})
);
}
mapToUpdatedState(cart: Cart): CartState {
const formatOptions = { style: "currency", currency: "EUR" };
return {
kind: "UpdatedCartState",
open: this.state.open,
totalItems: cart.totalItems,
totalPrice: cart.totalPrice.toLocaleString("es-ES", formatOptions),
items: cart.items.map(cartItem => {
return {
id: cartItem.id,
image: cartItem.image,
title: cartItem.title,
price: cartItem.price.toLocaleString("es-ES", formatOptions),
quantity: cartItem.quantity,
};
}),
};
}
}
The base class of all PLoCs is responsible for storing the state and notifying when it changes.
type Subscription<S> = (state: S) => void;
export abstract class Ploc<S> {
private internalState: S;
private listeners: Subscription<S>[] = [];
constructor(initalState: S) {
this.internalState = initalState;
}
public get state(): S {
return this.internalState;
}
changeState(state: S) {
this.internalState = state;
if (this.listeners.length > 0) {
this.listeners.forEach(listener => listener(this.state));
}
}
subscribe(listener: Subscription<S>) {
this.listeners.push(listener);
}
unsubscribe(listener: Subscription<S>) {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
}
}
All the information that the UI component needs must be interpreted from the state, elements to render in a table or list, but also if something should be visible or not, such as the shopping cart, the loading, or an error to show.
export interface CommonCartState {
open: boolean;
}
export interface LoadingCartState {
kind: "LoadingCartState";
}
export interface UpdatedCartState {
kind: "UpdatedCartState";
items: Array<CartItemState>;
totalPrice: string;
totalItems: number;
}
export interface ErrorCartState {
kind: "ErrorCartState";
error: string;
}
export type CartState = (LoadingCartState | UpdatedCartState | ErrorCartState) & CommonCartState;
export interface CartItemState {
id: string;
image: string;
title: string;
price: string;
quantity: number;
}
export const cartInitialState: CartState = {
kind: "LoadingCartState",
open: false,
};
In this case through union types of typescript, we can more securely and functionally model our state using sum algebraic data types.
This way of modeling is less prone to errors because you indicate that a very clear form that the state has 3 main possibilities:
- Loading information
- An error has occurred
- Updated data
Presentation Layer — UI
In this layer is where are the components and everything related to React or Vue such as components, hooks, applications, etc.
The components are very simple and light because they are free to manage any type of logic or state management, this is the responsibility of each of the layers in the core package.
React App
In react we will have the components that render our list of products, the app bar with the number of products in the cart, and the product cart rendered as a Sidebar.
Let’s see the example of the component that renders the content of the cart.
import React from "react";
import { makeStyles, Theme } from "@material-ui/core/styles";
import { List, Divider, Box, Typography, CircularProgress } from "@material-ui/core";
import CartContentItem from "./CartContentItem";
import { CartItemState } from "@frontend-clean-architecture/core";
import { useCartPloc } from "../app/App";
import { usePlocState } from "../common/usePlocState";
const useStyles = makeStyles((theme: Theme) => ({
totalPriceContainer: {
display: "flex",
alignItems: "center",
padding: theme.spacing(1, 0),
justifyContent: "space-around",
},
itemsContainer: {
display: "flex",
alignItems: "center",
padding: theme.spacing(1, 0),
justifyContent: "space-around",
minHeight: 150,
},
itemsList: {
overflow: "scroll",
},
infoContainer: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100vh",
},
}));
const CartContent: React.FC = () => {
const classes = useStyles();
const ploc = useCartPloc();
const state = usePlocState(ploc);
const cartItems = (items: CartItemState[]) => (
<List className={classes.itemsList}>
{items.map((item, index) => (
<CartContentItem key={index} cartItem={item} />
))}
</List>
);
const emptyCartItems = () => (
<React.Fragment>
<Typography variant="h6" component="h2">
Empty Cart :(
</Typography>
</React.Fragment>
);
switch (state.kind) {
case "LoadingCartState": {
return (
<div className={classes.infoContainer}>
<CircularProgress />
</div>
);
}
case "ErrorCartState": {
return (
<div className={classes.infoContainer}>
<Typography display="inline" variant="h5" component="h2">
{state.error}
</Typography>
</div>
);
}
case "UpdatedCartState": {
return (
<React.Fragment>
<Box flexDirection="column" className={classes.itemsContainer}>
{state.items.length > 0 ? cartItems(state.items) : emptyCartItems()}
</Box>
<Divider />
<Box flexDirection="row" className={classes.totalPriceContainer}>
<Typography variant="h6" component="h2">
Total Price
</Typography>
<Typography variant="h6" component="h2">
{state.totalPrice}
</Typography>
</Box>
</React.Fragment>
);
}
}
};
export default CartContent;
Hooks
Using Clean Architecture, hooks are not used? Yes, they are used, but for what is strictly necessary.
The state will not be managed with hooks, the side effects are not triggered from hooks, this is the responsibility of the PloCs in the core package.
But we will use them to store the final state of the component that its PloC returns to us and we will use them to share context between components or react to the change of state that the PloC returns to us.
Let’s see how the usePLocState hook that we used in the component is defined:
export function usePlocState<S>(ploc: Ploc<S>) {
const [state, setState] = useState(ploc.state);
useEffect(() => {
const stateSubscription = (state: S) => {
setState(state);
};
ploc.subscribe(stateSubscription);
return () => ploc.unsubscribe(stateSubscription);
}, [ploc]);
return state;
}
This custom hook is in charge of subscribing to the PloC state changes and storing the final state.
Vue App
In Vue, we will also have the same components as in the React version.
Now let’s see the component that renders the content of the shopping cart in the Vue version:
<template>
<div id="info-container" v-if="state.kind === 'LoadingCartState'">
<ProgressSpinner />
</div>
<div id="info-container" v-if="state.kind === 'ErrorCartState'">Error</div>
<div id="items-container" v-if="state.kind === 'UpdatedCartState'">
<div v-if="state.items.length > 0" style="overflow: scroll">
<div v-for="item in state.items" v-bind:key="item.id">
<CartContenttItem v-bind="item" />
</div>
</div>
<h2 v-if="state.items.length === 0">Empty Cart :(</h2>
</div>
<Divider />
<div id="total-price-container">
<h3>Total Price</h3>
<h3>{{ state.totalPrice }}</h3>
</div>
</template>
<script lang="ts">
import { defineComponent, inject } from "vue";
import { CartPloc } from "@frontend-clean-architecture/core";
import { usePlocState } from "../common/usePlocState";
import CartContenttItem from "./CartContenttItem.vue";
export default defineComponent({
components: {
CartContenttItem,
},
setup() {
const ploc = inject<CartPloc>("cartPloc") as CartPloc;
const state = usePlocState(ploc);
return { state };
},
});
</script>
<style scoped>
#info-container {
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
#items-container {
display: flex;
flex-direction: column;
align-items: center;
min-height: 150px;
justify-content: space-around;
}
#total-price-container {
display: flex;
align-items: center;
padding: 8px 0px;
justify-content: space-around;
}
</style>
As you can see, it looks a lot like the React version using composition API.
Composition API
In the Vue version we will also have hooks, such as the one that manages the subscription to changes in the PLoC state:
import { Ploc } from "@frontend-clean-architecture/core";
import { DeepReadonly, onMounted, onUnmounted, readonly, Ref, ref } from "vue";
export function usePlocState<S>(ploc: Ploc<S>): DeepReadonly<Ref<S>> {
const state = ref(ploc.state) as Ref<S>;
const stateSubscription = (newState: S) => {
state.value = newState;
};
onMounted(() => {
ploc.subscribe(stateSubscription);
});
onUnmounted(() => {
ploc.unsubscribe(stateSubscription);
});
return readonly(state);
}
Dependency Injection
From the React and Vue app, we have to create or reuse the PloC structure for each component: use cases and repositories.
If these concepts were defined in the core package, the part responsible for creating them may be in the core package as well.
This time I am using the Service Locator pattern statically:
function provideProductsPloc(): ProductsPloc {
const productRepository = new ProductInMemoryRepository();
const getProductsUseCase = new GetProductsUseCase(productRepository);
const productsPloc = new ProductsPloc(getProductsUseCase);
return productsPloc;
}
function provideCartPloc(): CartPloc {
const cartRepository = new CartInMemoryRepository();
const getCartUseCase = new GetCartUseCase(cartRepository);
const addProductToCartUseCase = new AddProductToCartUseCase(cartRepository);
const removeItemFromCartUseCase = new RemoveItemFromCartUseCase(cartRepository);
const editQuantityOfCartItemUseCase = new EditQuantityOfCartItemUseCase(cartRepository);
const cartPloc = new CartPloc(
getCartUseCase,
addProductToCartUseCase,
removeItemFromCartUseCase,
editQuantityOfCartItemUseCase
);
return cartPloc;
}
export const dependenciesLocator = {
provideProductsPloc,
provideCartPloc,
};
We could also use a dynamic Service Locator together with Composition Root or a dependency injection library.
In the React app, there is a global state that must be shared, it is the shopping cart. Therefore CartPloc, which is the one who manages this state, must be shared and accessible by all components.
React
In React we solve this using createContext and a custom hook using useContext.
export function createContext<T>() {
const context = React.createContext<T | undefined>(undefined);
function useContext() {
const ctx = React.useContext(context);
if (!ctx) throw new Error("context must be inside a Provider with a value");
return ctx;
}
return [context, useContext] as const;
}
const [blocContext, usePloc] = createContext<CartPloc>();
export const useCartPloc = usePloc;
const App: React.FC = () => {
return (
<blocContext.Provider value={dependenciesLocator.provideCartPloc()}>
<MyAppBar />
<ProductList />
<CartDrawer />
</blocContext.Provider>
);
};
export default App;
Using the custom useCartPloc we have access from any component to this PloC and its state.
Vue App
In Vue, we solve this by using the provide feature.
<template>
<div id="app">
<MyAppBar />
<ProductList searchTerm="Element" />
<CartSidebar />
</div>
</template>
<script lang="ts">
import { dependenciesLocator } from "@frontend-clean-architecture/core";
import { defineComponent } from "vue";
import MyAppBar from "./appbar/MyAppBar.vue";
import ProductList from "./products/ProductList.vue";
import CartSidebar from "./cart/CartSidebar.vue";
export default defineComponent({
name: "App",
components: {
ProductList,
MyAppBar,
CartSidebar,
},
provide: {
cartPloc: dependenciesLocator.provideCartPloc(),
},
});
</script>
Later from any component, we have access to the PLoC and its state using:
const cartPloc = inject <CartPloc> (“cartPloc”) as CartPloc;
Source code
The source code can be found here: frontend-clean-architecture.
Related Articles And Resources
- Spanish newsletter: https://xurxodev.com/#/portal/signup
- Clean Architecture: A Craftsman’s Guide to Software Structure and Design
- Clean Architecture Course.
- ¿Wy use I Clean Architecture in my projects?
- The Bloc Pattern in Clean Architecture
- The BLoC Pattern in Clean Architecture in ReactJS
- The BLoC Pattern in Clean Architecture in Flutter
- Clean Architecture: Code Smells. Parte 1
- Clean Architecture: Code Smells. Parte 2
- My surreal purchase of the book Clean Architecture
Conclusions
In this article, we have seen a Clean Architecture implementation on the front-end.
We have a version of React and Vue app reusing as much code as possible between the two and placing it in a core package.
With this exercise of having a core package with all the logic uncoupled from the framework, we can appreciate the power that Clean Architecture can offer us on the front-end.
Organizing the project as a monorepo and having a core package has been necessary for this example, but it is not necessary when developing an app either React or Vue.
However, it is an interesting exercise to force you to uncouple from the UI framework as it can sometimes be difficult to see that you are coupling, especially at the beginning.
Posted on July 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.