SOLIDify Your React Code

Rate this content
Bookmark
Slides

Writing a cleaner Code in React by following SOLID Principles

This talk has been presented at React Day Berlin 2023, check out the latest edition of this React Conference.

Watch video on a separate page

FAQ

Islam Aboud is a full stack software engineer working with TopTel, the founder of the Code One YouTube channel, and a creator of educational tutorials and blog posts on web application development.

SOLID principles can be applied to React by adapting them to fit the framework’s workflow. This involves ensuring components have single responsibilities, can be extended without modification, are swappable within the same type, do not depend on unnecessary props, and rely on abstractions rather than concrete implementations.

In React, the Single Responsibility Principle (SRP) means that every component should do exactly one thing and thus have only a single reason to change. This makes the code easier to read and maintain.

In React, the Liskov Substitution Principle (LSP) ensures that child components should be easily swappable with other components of the same type. This allows for more flexible and maintainable code.

The Interface Segregation Principle (ISP) in React means that components should not depend on props they do not need. This prevents the creation of overly large and monolithic interfaces, ensuring that components receive only the props they actually use.

TypeScript is used with React to implement SOLID principles because JavaScript does not natively support object-oriented programming (OOP) features as strongly as TypeScript does. TypeScript allows for the necessary adaptations to apply SOLID principles effectively in a React environment.

The Open Close Principle (OCP) in React states that a component should be easily extended without modifying the underlying source code. This is achieved by designing components that can handle additional features through external inputs rather than internal changes.

The Dependency Inversion Principle (DIP) in React promotes decoupling higher-level modules from lower-level modules by depending on abstractions rather than concrete implementations. This enhances flexibility, extensibility, and maintainability.

Clean Code refers to code that can be easily understood, read, and enhanced by any developer on a team, not just the original author. It emphasizes readability, changeability, extensibility, and maintainability.

SOLID principles are five design tenets introduced by Robert C. Martin to create scalable and maintainable object-oriented software. They are Single Responsibility Principle, Open Close Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle.

Islem Maboud
Islem Maboud
11 min
12 Dec, 2023

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Clean code is easily understood, readable, changeable, extensible, and maintainable. SOLID principles enforce good practices for scalable and maintainable software. The Single Responsibility Principle (SRP) ensures that components have a single reason to change. The Open-Close Principle (OCP) allows components to be easily extended without modifying the underlying source code. The Liskov Substitution Principle (LSP) enables swapping child elements within a subtype component. The Interface Segregation Principle (ISP) states that components should only depend on the props they actually use.
Available in Español: SOLIDifica Tu Código React

1. Introduction to Clean Code and SOLID Principles

Short description:

Hi everyone. I'm Islam Aboud, a full stack software engineer working with TopTel. Today, we'll cover Intro to Clean Code and the five SOLID principles. Clean code is easily understood, readable, changeable, extensible, and maintainable. SOLID principles, introduced by Robert C. Martin, enforce good practices for scalable and maintainable software. They are Single Responsibility, Open Close, LispConv Substitution, Interface Segregation, and Dependency Inversion. SOLID works well in team environments, and using TypeScript with React allows for cleaner code following these principles.

Hi everyone. I'm Islam Aboud and welcome to today's talk about solidifying your React code. So a little more about me. I'm Islam Aboud, a full stack software engineer working with TopTel. I'm the founder of the Code One YouTube channel at youtube.com codeone. Also, I'm a big fan of helping developers build better web applications with like educational tutorials and video tutorials on YouTube and blog posts and stuff. And you can find my portfolio at islamaboud.com.

So this is what we are going to cover today from Intro to Clean Code to actually going through the different solid principles and exactly how you can apply them inside of React. So first, let's go ahead and see a quick introduction into Clean Code. So code, we tell or we say code is an actual clean code if it can be understood easily by everyone on the team. So clean code can be read and enhanced by the developer other than its original author. So anybody on the team, even though he's not like the right person or the original person who wrote that piece of code, he can easily understand exactly what's happening. So with understandability comes readability, changeability, extensibility, and most importantly, maintainability. So here it can actually read about, you know, clean code, best practices, and how to write clean code. What is the best practices to make your code cleaner, easier to read by everyone, and of course, eventually, you would actually be able to write better code.

Now when it comes to solid principles, there are actually five design tenets known as solid and are actually used to create scalable and maintainable object-oriented software. They're originally introduced by Robert C. Martin. He's the guy that originally wrote and actually published the Clean Code book, and actually he first proposed these ideas inside of that book. Then, since that one, they have been actually involved into guiding of how to write cleaner code in different places. And one of these places is React. So there are actually five of them starting with the Single Responsibility Principle, the Open Close Principle, LispConv Substitution Principle, Interface Segregation Principle, and most importantly, Dependency Inversion Principle. So SOLID enforces actually a set of good practices that basically is going to allow you to write simpler, easier to read and cleaner or better code, and it particularly works really, really well especially when working in a team environment. So if you're working with a team of developers, actually following the SOLID principles, it's going to help you a lot writing cleaner code that can be understand and maintained by everyone on the team. And of course these principles are originally crafted and created for the object oriented programming so something like Java maybe or C++. Some languages actually has an OOP. But of course, because we use JavaScript with React a lot, JavaScript isn't a language that actually supports OOP a lot, so we have to actually introduce and use the older brother of JavaScript, which is TypeScript. So using TypeScript with React, it can allow us to write cleaner code following the SOLID principles. Of course, we will have to do a minor adaption and small teeny tiny thing change to those SOLID principles to make it work the React workflow. So let's go ahead and see SOLID principles applied in React.

2. Single Responsibility Principle (SRP)

Short description:

The single responsibility principle (SRP) states that every component should do exactly one thing. It ensures that components and functions have a single reason to change. For example, a bad component may have multiple responsibilities, making it hard to read and understand. In contrast, a good component follows SRP by encapsulating logic in hooks and rendering encapsulated components.

So starting with the single responsibility principle or the SRP. So for the original definition, every class should have only one responsibility for the extrapolated definition to make it work with React. So every component should do exactly one thing. So SRP is the role to making sure our component and functions or modules are responsible for doing one thing only and thus have only a single reason to change.

So to better understand SRP, for example we can take this simple React component here which is like the bad component here. So it's a normal component. It uses the useState in here. It has a function to fetch the product, has a useFx in here to call the fetching of the product and here's some function to handle the rating and the button click and everything another one using usingMemo to filter the products depending on the rating. And of course it renders a bunch and I mean a bunch like a lot of GSX in here. All of it is actually really complicated and it's really hard to read. You don't know exactly what's happening. So all the filtering stuff are happening. The rating component is being rendered. I'm like mapping through the SVG here to render the stars or the rating stars and a bunch of stuff and literally very hard to read. Now if we go into a better implementation like the good component here, it's a lot better and now it uses actually a hook which is used products to do the fetching. That actually has encapsulated all the fetching. Use another one. Use rate filtering here to do the filtering stuff. So everything is encapsulated inside of that hook and we just render these two components. So everything, all the logic in the GSX has been encapsulated into like the filtering component and here we're just mapping it and we're rendering this encapsulated product component.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

SolidJS: Why All the Suspense?
JSNation 2023JSNation 2023
28 min
SolidJS: Why All the Suspense?
Top Content
Suspense is a mechanism for orchestrating asynchronous state changes in JavaScript frameworks. It ensures async consistency in UIs and helps avoid trust erosion and inconsistencies. Suspense boundaries are used to hoist data fetching and create consistency zones based on the user interface. They can handle loading states of multiple resources and control state loading in applications. Suspense can be used for transitions, providing a smoother user experience and allowing prioritization of important content.
Facing Frontend's Existential Crisis
React Summit 2024React Summit 2024
37 min
Facing Frontend's Existential Crisis
I'm honored to be here today. The past decade has been dominated by single-page apps. Loading JavaScript is about 35 times slower than images on low-end devices. Server rendering involves sending more JavaScript and HTML, increasing payload and effort. React was developed for complex apps, but business needs have pushed towards simpler websites. Metrics for testing frameworks include code execution costs, bundle size, and payload size. Islands, popularized by frameworks like Astro and Fresh, break up apps into sections for server rendering. React's solution is to use islands and communicate in a diffing format. Quik reduces code execution and size, eliminating double-serializing. Frameworks like Solid Start provide tools for server rendering in a lightweight package. WASM frameworks have improved in performance. Next.js partial pre-rendering and HTMX offer solutions for sites with less interactivity.
SolidStart 1.0: Peeking Under the Hood
React Summit 2024React Summit 2024
30 min
SolidStart 1.0: Peeking Under the Hood
SolidStart is an efficient, unopinionated, and ergonomic full-stack framework that provides great defaults and flexibility. It includes features such as a bundler, a serializer, a server, and a router. The serializer, Seroval, enables streaming and real-time state synchronization between server and client. SolidStart offers powerful file routes, RPCs, and single-flight mutations. It is recommended for building UIs in full applications, Spark, single-page apps, and native apps.