To read more articles like this, visit my blog
Programming is often considered a craft rather than a job. There are good reasons for it too. We as developers should always try to achieve the best quality in any software we write. And there are some awesome principles to follow as a blueprint. One of my favorites is: “DRY — Don’t Repeat Yourself”
Today I will share 5 techniques that I use personally to avoid duplication of code in my project.
1. HTTP Calls
fetching data from some remote store is one of the most common tasks in any modern React application. Beginners do a lot of mistakes in this. Here are the common evolution of a project
Step 1. Fetching data inside component
At first, people try to fetch data inside the component itself. (because most tutorials show us that)
Step 2. Abstract away the logic into some kind of store
In this step, people take away the logic outside their component and put them inside the store management(Like redux or context). But there is still a lot of duplicates in the codes.
How to ‘DRY’ it up
First Way: Try to create a separate HttpUtility
class or custom useHttp
hook for managing all your HTTP calls. You can use axios
for handling the remote call part for you. But detecting loading state and handling errors can be tricky for you.
A Better Approach: Take some time to learn some awesome library react-query It provides you with some great functionalities that can be useful for any application size.
2. Error Handling
In my experience, I have seen people mess this up in many places. Calling toasts in every component is not a good idea generally. There are some common scenarios where we want to give some feedback to the user.
1. Error in HTTP call
Middlewares (They intercept any action before going to the redux store) are great for handling most errors. Intercept the errors that came back from the HTTP call and show a toast. In my redux setup, I do it like this
const ErrorMiddleware = (state) => (next) => (action) => {
const response = action.payload;
if (response instanceof HttpErrorResponseModel) {
next(CommonAction.showErrorToast(action.payload.message))
}
next(action)
}
2. Error in Component logic
We can implement the idea of ErrorBoundary catching all the errors related to component loading issues. This way we don’t need to put null checks everywhere.
3. Validation Error
Another time we want to show error toasts to the user is when something goes wrong with the validation of some form that is filled up by the user.
Try to use some kind of form-validation library(like Yup
) to handle the validation errors and giving feedback to the users automatically. Or you can use libraries like react-hook-form to do it for you!
3. Composition of Components
I guess this is a no-brainer. But oftentimes people starting with react fail to understand the most powerful feature of React. That is Reusable Component
Always try to break down components into smaller pieces. It has multiple benefits.
It improves code quality and readability
Same UI components are not duplicated across the project
4. Use Custom Hooks
I am personally a big fan of hooks and I think new developers should learn this as early as possible.
Whenever any logic is duplicated and we want to abstract away the logic. React has provided us with solutions like HOC(Higher Order Component)
import React from "react";
const withDataFetching = props => WrappedComponent => {
class WithDataFetching extends React.Component {
render() {
return (
<WrappedComponent />
);
}
}
return WithDataFetching;
};
export default withDataFetching;
Although hooks are used generally for the same purpose they achieve this in a much more cleaner fashion. The previous code can be re-written like this!
import React, { useState, useEffect } from "react";
function useDataFetching(dataSource) {
return {};
}
export default useDataFetching;
5. Avoid Duplicate Styling
Styling has always been a great pain for me. And I believe the case is the same for other beginners also. For me, evolution as a developer looked something like this.
Step 1. Using .css
files for styling components.
As we know if you are not skilled at organizing your style files properly you can get lost in the world of duplicated CSS logic.
Step 2. At this stage, I learned Sass
It’s great for writing CSS in a modular fashion. It provides the ability to re-use CSS codes and introduces the concepts of mixin and variables in CSS. But still, I found it difficult to manage. Maybe that’s partly my fault
Finally, I came across styled-components which is an awesome library to re-use styles for components. For me, it helps to create much more readable components and no more className
inside my code!
Here is an example of a styled component in action
const StyledButton = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
Conclusion
There you go. These are some techniques you can apply to your project in order to follow the DRY principle in React. These are not bulletproof solutions but understanding how all these works can take you a long way.
If you are interested in advanced best practices, here is another article for you.
Have a great day! :D
Get in touch with me via LinkedIn or my Personal Website.