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! 😎

Phiter Fernandes's photo

I'm a big fan of Vue.js, even being a contributor to some projects in its ecosystem, but for the past 8~9 months I've been working with React and even though I like many parts of Vue better, I think React is a powerful tool and the way components are handled is pretty neat.
But if you're learning/working with React, I can't recommend Typescript enough.
I was super scared of Typescript at first, always looked at it like "ugh" but once I started actually working with it, it just makes development so much better. It feels more professional, you get type safety in your components and nice DX powered by autocomplete in VSCode or other IDEs, for component props for example.
So, learn React, make your code clean with the tips here but as soon as you can, try and add Typescript to your skillset. It will change your life.

Luísa Ribeiro Bezerra's photo

Thank you, Phiter! It is nice to know how strong and good the typescript is, and how it helps the developer to write clean code! As soon as I have the chance to use it professionally, I will definitely be very happy :)

Michele Masina's photo

The part about destructuring props is not completely correct. The second example shows:

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

while the third example shows:

const UserCard = ({ name, age, phone })=> {

It should read instead:

const UserCard = ({ user })=> {

and be used as user.name or user.age, or even better:

const UserCard = ({ user: { name, age, phone } })=> {

and be used simply with name or age.

Other than that, good article. Thanks! :)

Luísa Ribeiro Bezerra's photo

Thank you Michele! I have already edited it, thanks to Arthur (and you, ofc). I didn't notice it while I was writing this post! So thank you again :)

Stela IS's photo

A clean code based on a clean post :)

Love the tips!!! I feel like my scripts will smell like lavender now!

Luísa Ribeiro Bezerra's photo

Thank you again, Stela <3

Arthur Corenzan's photo

Hi Luiza, those are some great tips, thank you for this post!

Just one thing though. I would advise against the use of boolean && over the ternary operator. Here's a cautionary tale: kentcdodds.com/blog/use-ternaries-rather-th..

TL;DR is that the operator && might evaluate to the first value whereas the ternary will only evaluate to the explicit expressions you type in second and third positions. While the code is new and short it's clear to see, but once enough time has past and enough keyboards have touched it things get messier and bugs like these creep in.

Have a great day! ☺️

Luísa Ribeiro Bezerra's photo

Oh lord! I'll add this info in the text :) thank you very much!

Arthur Brière's photo

Thank's for the article ! I juste have a little comment about this part :

const UserCard = ({ name, age, phone })=> {

On your previous examples, those props (name, age, phone) are children of props.user, not props directly.

But it's quite nothing !

Luísa Ribeiro Bezerra's photo

Yeaah, good point, so based on this example, you must pass the props.user as "props". Thank you for collaborating :D

Smile Gupta's photo

Amazing one Luísa Ribeiro Bezerra Totally loved it. ❤️ Just one question where can I find this eslint-plugin-import plugin? I checked in extensions of VS Code it was not there.

Luísa Ribeiro Bezerra's photo

Hi dear! This plugin you need to install and you can follow the steps on this link: github.com/benmosher/eslint-plugin-import#i..

Thank you again, and if you have any doubts just ask me :)

Matheus Ribeiro's photo

Great post! I liked specially the parts about how to organize imports (I already kind of did that but had no formal rule for this, I just absorbed it from what I had seem before), and the one about one-conditional rendering. It's great because ternary conditional expressions can look so damn ugly inside JSX code. I'm definitely using this in the future!

By the way, it's not always that we see an article by a fellow Brazilian having so much traction inside the developer community! Great job! I'm looking forward for your next posts!

Luísa Ribeiro Bezerra's photo

Thank you SO MUCH for this comment! It for sure makes me wanna post every week hahahaha be my guest here :) anything you need please contact me!