React Clean Code for Beginners

React Clean Code for Beginners

Featured on Hashnode

Subscribe to my newsletter and never miss my upcoming articles

When I first started coding, what most caught my attention was the code pattern that is commonly used by Front-End developers, especially React developers. One of the things that I worked on the most was understanding how to architecture my entire project so that it followed certain standards that are considered "good code practices" :)

In this post, I will share with all of you 4 tips to write a clean (and better) code!

ESLint and Prettier: ON!

As I am an ESLint lover, I will try to convince you that you MUST use it! By adding ESLint in our code editor and our project, we can save time by finding an error while you are developing, and it will constantly make you aware of React best practices! 😍 Moreover, it is possible to set up specific ESLint rules and style guides, which the three most famous are Google JavaScript Style Guide, Standard JavaScript Style Guide and Airbnb JavaScript Style Guide. The ESLint rules that Airbnb abides by are considered among many as the gold standard for React 💎

Prettier is a code formatter, and it will take care of how your code looks. It can be enabled for the entire project, and it will completely rewrite your code according to a set of rules, standardizing the project. DON'T PANIC: it will only change the structural view, not the content! Prettier supports JavaScript, TypeScript, HTML, CSS, JSON, YML, and GrapQL, as well as frameworks like Angular, Vue, and React. Spend your time thinking about what to write and not how to write it!

Sort your Import Modules

Sorting your imports makes it easier to read and adds a light-weight hierarchical structure to it. It is much easier to understand the dependency network between all of the modules in your project. Sometimes, to do it manually is a little bit annoying, but here the ESLint can help us again <3

ESLint comes with in-built import sorting rules, but it is not the main point: eslint-plugin-import is a plugin that extends the ESLint import rules. It doesn't have properties only to organize and to sort - it also helps to prevent having issues like misspelling file paths or packages names, etc. The order is as shown in the following example, taken from its documentation:

// 1. node "builtin" modules
import fs from 'fs';
import path from 'path';
// 2. "external" modules
import _ from 'lodash';
import chalk from 'chalk';
// 3. "internal" modules
// (if you have configured your path or webpack to handle your internal paths differently)
import foo from 'src/foo';
// 4. modules from a "parent" directory
import foo from '../foo';
import qux from '../../foo/qux';
// 5. "sibling" modules from the same or a sibling's directory
import bar from './bar';
import baz from './bar/baz';
// 6. "index" of the current directory
import main from './';
// 7. "object"-imports (only available in TypeScript)
import log = console.log;

Unassigned imports are ignored, as the order that they are imported in may be important. Statements using the ES6 import syntax must appear before any require() statements.

Destructuring Syntax

ES6 definitely introduced a lot of new features to the JavaScript community, and one of them that I most love to use is object destructuring. It can reduce repetition in your code ( DRY principle of coding!!!), make the code better to read and understand, and help us to deal with a lot of values and parameters. Let's take an example:

const UserCard = props => {
  return (
    <div>
      <h1>{props.user.name}</h1>
      <p>Age: {props.user.age}</p>
      <p>Phone: {props.user.phone}</p>
    </div>
  );
};

Ok, in fact, this is not thaaaaat... good. We repeat "props.user" a lot, but we can get rid of it in a simple way, destructuring this object:

const UserCard = props => {
  const { name, age, phone } = props.user;

  return (
    <div>
      <h1>{name}</h1>
      <p>Age: {age}</p>
      <p>Phone: {phone}</p>
    </div>
  );
};

We have a third option that is to destructure "props" directly in the parameters:

const UserCard = ({ user: { name, age, phone } })=> {
  return (
    <div>
      <h1>{name}</h1>
      <p>Age: {age}</p>
      <p>Phone: {phone}</p>
    </div>
  );
};

And... voilààà, the code is much cleaner than the first version!

Simplify One-Conditional Rendering

It is common to use ternaries when we want to display a conditional in which we have two types of behavior based on a condition. But sometimes, we have a condition that, when true, we render something, but when false, we don't want to render anything. In this case, the best tip is to avoid using ternaries!

To illustrate, this is not the best way to render the button:

<div>
  {showButton? <Button> You can see me now! </Button> : null}
</div>

Here we can see that the one-conditional rendering works better:

<div>
  {showButton && <Button> You can see me now! </Button>}
</div>

ALERT: There are some "weirdo" behaviors when using the && in JavaScript. It might evaluate to the first value whereas the ternary will only evaluate to the explicit expressions you type in second and third positions. You can check the complete explanation here!


Thank you for reading and supporting me again 💜 I am preparing a new post, where I will give some tips to write better Functional React Components.

Stay tuned! 😎

 
Share this