9 Tips for Writing Clean, Fast, And Maintainable React Code
Tags: javascript, react, programming
Published: 2023-07-28 15:45:47

React Components In Code Editor
Make Your Work Clean, Fast, and Easy to-Maintain.
I know — this is every programmer’s goal (or at least I hope it is).

And, in my opinion, this skill separates a good programmer from a superb programmer.

The best part is that it is never truly finished because there is always something new to learn and improve on.

Following these tips can make things simpler not just for you, but also for your teammates.

I’ve seen development teams develop a style guide in which they set key principles for how they write code.

If you ask me, it’s a brilliant concept.

Among them were:

make advantage of functional components (like arrow functions)
Inline styles should not be used.
keep a good import structure (third-party imports first, next internal imports)
Before committing your code, format it.
And the like.

Of course, you could go into considerable detail about it. This is decided by your team.

Personally, I hate detailed style guides because I believe that as a skilled developer, you should have some degree of freedom and should not be overly limited.

However, a style guide in general is a smart way to outline and promote the best tips while also verifying that your team is on the same page in some key areas.

This, I find, greatly improves teamwork and productivity.

Let’s look at what those best tips are for creating clean, highly functional, and maintainable components.

Make yourself comfortable, get something to take notes with, and have fun!

Create an effective folder structure.
Effective Folder Structure In Code Editor
Always Try To Maintain Folder Structure
Maintainability and flexibility need you to structure your files and directories within your React application.

A proper folder structure is based on the complexity of your app and the size of your team.

As a result, there is no ultimate solution.

Especially since this is a widely controversial point that also depends on personal tastes.

However, some best tips for different software sizes have been developed over time.

This outstanding blog post covers 5 different app sizes and offers helpful suggestions for organizing your files and folders.

Keeping this in mind as you prepare or start your app might have a major impact in the long run.

Really shouldn’t, but do your best to keep a clear structure that is fit for your current application and team size.

Maintain a structured import order
React Illustration
Put Import Order in Manner
If you’ve worked with React before, you’ve probably seen files that are bloated with a lot of import statements.

They could also be mixed up with third-party package external imports and internal imports such as other components, util functions, styles, and many more.

Example from the Real World (cut):

Standard Version Of Import Order
This is an example of a normal import order.
You’re undoubtedly aware of what’s happening here.

It’s difficult to distinguish the difference between third-party and local (internal) imports.

They are not organized and seem to be distributed.

Improved Version:

Improved Version Of Import Order
This is an example of an improved version of the import order.
The structure is smoother, and it is much simpler to distinguish between external and internal imports.

Of course, you can improve it by using more named imports (if that’s possible! :)).

This allows you to import all of the components from material-ui on a single line.

Other developers, I’ve seen, like to break the import structure into three sections:

Internal → External (third-party node modules) → Built-in (like react).

You can do it yourself every time or hire a linter.

Here’s an excellent post on tweaking your linter for your React project to guarantee proper import structure.

Explore higher-level component patterns.
Component Pattern Including Three Components
An Effective Component Pattern
Learning new component patterns as you gain experience with React is important to avoiding unmaintainable and unscalable mess code.

But that’s not all.

Understanding the various patterns is an excellent starting point.

But the most important aspect is that you understand when to use which pattern for which situation.

Every pattern has a specific purpose.

For example, the compound component pattern avoids needless prop-drilling of many component levels.

So, the next time you pass props via five component levels to better than theirs the component that is interested in the props, you start organizing the components differently.

I’ll make a little comment about props drilling because I’ve had many discussions about it in the past.

There are many varying opinions on whether it is good or bad.

If I start passing props via more than two component levels, I try to think of a better way/pattern.

The truth increases your development efficiency and makes the components you design more robust and flexible.

Having such patterns in your toolset separates you from other React developers.

I strongly advise you to do your research, but this Udemy course was quite useful to me.

Use a linter and follow its guides.
Linter Features in Code Editor
How Linter Helps You In Code Editor
A linter can help you with more than just maintaining your dependencies in a unique import order.

It usually helps you create better code.

ESLint is fully set when you use create-react-app, but you can also create it completely on your own or extend the rules of a which were before the rule.

A linter examines the JavaScript code you’re writing and warns you of mistakes that you’d more likely see if you run the code.

It took some time for me to understand the use of a linter, but now I can’t imagine working without one.

It’s one thing to have the linter, but it’s entirely different to follow its guidelines.

Of course, you can turn it off. Either for a certain line of code or the whole file.

There could be situations when this makes sense, but in my experience, they are extremely rare.

Another major benefit is the ability to adjust style checkers. This is very useful for teams.

You can easily combine ESLint with something like JSPrettify if you’ve agreed on some guidelines for how you write your code and how it should be structured.

Put your code to the test.
An Laptop Testing Code
Test Your Code In Every Routine Day
I understand that testing is probably not your favorite activity as a developer.

That was how I used to be.

At first, it seemed to be a useless and painful activity.

This might be true in the short run. But, in the long run — especially as the application expands — it is important.

Testing has become a routine for me that guarantees I’m performing my job properly and delivering higher-quality code.

There is nothing wrong with manual testing by humans, and it should not be avoided entirely.

However, say you are integrating a new feature and want to verify that nothing is broken.

This can be a time-consuming and error-prone activity.

You’re already thinking about how to structure your code to pass this test while you’re developing tests.

This is usually useful for me since I can predict future problems and keep a look out for them.

You’re not going right into creating code (which I wouldn’t recommend), but you’re thinking about the ultimate goal first.

As an example, “What should that specific component do? What important edge cases could arise that I must test? Can I clean the component such that it just serves one purpose? …”

Having a vision for the code you’re going to create can also help you stay focused on serving that vision.

Tests can also act as documentation in the sense that they can help a new developer who is new to the codebase understand the various elements of the product and how they are supposed to work.

So, don’t try to stay away from testing because it seems to be more work.

When configured correctly, it can save you time and effort in the future.

Explore the “Testing” section in the React Docs, watch a few tutorials on testing in React, and simply begin writing your first small TDD application or adding tests to an app you’re currently working on.

Typescript should be used (or use default props & proptypes)
TypeScript Banner
You should start using typescript or, at the minimum, the default props and prop types.
I remember my first React project as a software developer when our team was given a project that had previously been created in its entirety by another company.

Then we had to build the client’s project on top of it, and Typescript was already built in.

My teammates and I had no prior experience with TypeScript because we all came from a vanilla JavaScript background.

After a few weeks of working on that project, we decided that TypeScript was not an advantage, but rather a burden to our workflow.

We were also not getting the full benefits because we defined everything with type any to suppress Typescript warnings.

As a result, we decided to remove TypeScript from the project and stick to our tried-and-true vanilla JavaScript.

This worked smoothly at first, but as our project got more complicated, more errors appeared.

So we doubted our choice to quit TypeScript fully.

But such situations do happen and provide us with important experiences for the future.

This scenario inspired me to review TypeScript, which I studied in my spare time.

I can’t imagine my life without it now that I’ve built some side projects using it.

TypeScript has many advantages, like static type checking, better code completion in your IDE (IntelliSense), a better developer experience, and catching type errors as you write code — only to mention a few.

On the other side, it might offer some difficulties, because if you don’t come from a background with tightly typed languages (such as Java or C#), it could be difficult to understand at first.

But I can tell that learning and applying it is well worth the effort.

Here’s a good article that will provide you with an overview of the advantages and disadvantages of using Typescript in React apps.

And here’s a guide on writing TypeScript code for your React apps.

There may be reasons why you do not want to use TypeScript in your React project.

Make use of lazy loading & code splitting.
An Code Editor
Lazy Loading & Code Splitting is very useful in the workflow.
If you’ve spent any time in the JavaScript and React world, you’ve most likely come across the concept of bundling.

For those of you hearing this word for the first time, here’s what the official React documentation says:

Most React projects will use tools like Webpack, Rollup, or Browserify to “bundle” their files.

Bundling is the process of following imported files and joining them into a single file: a “bundle”.

This bundle can then be linked to a webpage to load the full app at once.

Basically, this is a fantastic strategy, but when your app expands, it will cause a problem.

Your bundle starts to grow as well.

Especially when using large third-party libraries such as three.js.

The disadvantage is that this bundle must always be loaded fully, even if the user just requires a section of the code.

This produces performance issues since your app can take an extra long time to load.

To avoid this, use a method known as code splitting, which separates your bundle into the pieces of code your user need.

The most popular bundlers, such as Webpack, Rollup, and Browserify, enable this.

The fact that you can build different bundles and load them dynamically is a huge advantage.

To clarify, say you’re heading to the grocery shop and only want bananas, apples, and bread.

In that case, you are not buying the entire shop and then selecting your bananas, apples, and bread from that too.

You’re only interested in a slice of the range. So, why would you buy everything?

It would take much longer and would be much more expensive.

I believe it is important to be aware of the potential issues which may arise as your app expands, and that there are ways available to address such concerns.

Check out the React documentation for more information.

Organize reusable logic into custom hooks
React Hook
Create your custom hooks
According to the React documentation,

Hooks let us reuse stateful code without having to change our forming.

Essentially, they are a superior answer to the methods that were previously used in combination with class components.

You might remember using Higher Order Components or render properties if you’ve been coding for a while.

When you need to reuse the same stateful logic that is already in use in another functional component, it’s a wonderful opportunity to develop a custom hook.

You wrap the logic within it and only need to call the hook as a function within your components.

Let’s look at a quick example where we need to change our UI based on screen size and want to keep track of the current window size while manually resizing the browser window.

const ScreenDimensions = () => {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });
  
  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    window.addEventListener('resize', handleResize);
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return (
   <>
     <p>Current screen width: {windowSize.width}</p>
        <p>Current screen height: {windowSize.height}</p>
    </>
  )
}
As you can see, the solution is pretty straightforward and there’s nothing wrong with defining it like this.

Now comes the tricky part.

Imagine we’d like to use the exact logic in another component, where we’ll render a different UI (one for smartphones and one for desktops) based on the current screen size.

Of course, we could just copy the logic, paste it in and we’re done.

But this is not a good tip, as you might know from the DRY principle.

If we’d like to adjust our logic, we have to do it in both components.

And when we paste our logic into even more components, it becomes less maintainable and more error-prone.

So, what would you normally do in a vanilla JavaScript project?

You’d most likely define a function that encapsulates the logic and can be used in many different places.

That’s exactly what we’ll achieve with hooks.

They are nothing more than JavaScript functions but with some React specialties because they’re using React hooks.

So, in a typical JavaScript project, what would you do?

Most likely, you’d build a function that encapsulates the logic and can be used in a variety of ways.

That is exactly what we will do using hooks.

They are nothing more than JavaScript functions with some React brilliance thanks to the use of React hooks.

Let’s have a look at our unique hook:

const useWindowSize = () => {
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });
  
  useEffect(() => {
    function handleResize() {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    window.addEventListener('resize', handleResize);
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  
  return windowSize;
}
Let’s just name it that inside our ScreenDimensions component:

const ScreenDimensions = () => {
  const windowSize = useWindowSize()
  
  return (
   <>
     <p>Current screen width: {windowSize.width}</p>
        <p>Current screen height: {windowSize.height}</p>
    </>
  )
}
This lets us simply call the custom hook from any other component and save the return value (the current window size) in a variable that we can use inside the component.

const ResponsiveView = () => {
  const windowSize = useWindowSize()
  
  return (
   <>
     {windowSize.width <= 960 ? (
          <SmartphoneView />
        ) : (
          <DesktopView /> 
        )}
    </>
  )
}
Handle errors correctly.
Errors on desk in front of man
Try to handle errors as best you can (It Time Saving)
Many developers ignore and underestimate the importance of error handling.

This seems to be a mistake from the start, as with many other best tips.

You want the code to work and don’t want to “waste” time thinking about errors.

However, as you gain experience and see situations where better error handling could have saved you a lot of energy (and valuable time), you know that having solid error handling inside your app is important in the long run.

Especially when the application is in service.

But what does error handling mean in the React world? There are a few parts that have a role.

One is to catch errors, another is to handle the UI properly, and the last is to properly report them.

Final words
That was a lot of fun, wasn’t it?

I tried my hardest to get everything out of my thoughts that had been collected over time.

My goal in writing this post is to share my experience with you to help you avoid some challenging times during your React learning and progress.

Of course, there may be great tips that you think are more important than I have missed. That’s awesome.

I’d love to hear anything you think should be added to this post.

Remember that it is always about changing what is useful to you.

So, don’t take things for granted, and think about what can be useful in your situation.

Then just add it to your list of best tips.

You can also follow me on Medium.

I’m always ready to help you and welcome any comments you can offer me.

So definitely don’t hesitate to speak with me.