DEV Community 👩‍💻👨‍💻

Cover image for React - Best Practices
Hafiz Muhammad Bilal
Hafiz Muhammad Bilal

Posted on

React - Best Practices

While working on a React App, following these coding conventions will give you a better development experience

VS Code is Highly Recommended as IDE

Visual Studio Code has several features that a React developer loves. It gives a lot of useful extensions to make the development environment better. For React, here are some useful extensions which will assist you during development

  • Prettier
  • ES Lint
  • JavaScript (ES6) code snippets
  • Reactjs code snippets
  • Auto import

Use ES6 Syntax

Clean code is always appreciated. In JavaScript, you can adopt ES6 syntax to make your code cleaner.

Write Arrow Functions

// ES5
function getSum(a, b) {
  return a + b;
}

// ES6
const getSum = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Use Template Literal

// ES5
var name = "Bilal";
console.log("My name is " + name);

// ES6
const name = "Bilal";
console.log(`My name is ${name}`);
Enter fullscreen mode Exit fullscreen mode

Use const & let

They have block scope. Variables with const declaration can't be changed but with let, they are mutable

// ES5
var fruits = ["apple", "banana"];

// ES6
let fruits = ["apple", "banana"];
fruits.push("mango");

const workingHours = 8;
Enter fullscreen mode Exit fullscreen mode

Object Destructuring

var person = {
  name: "John",
  age: 40,
};

// ES5
var name = person.name;
var age = person.age;

// ES6
const { name, age } = person;
Enter fullscreen mode Exit fullscreen mode

Defining Objects

var name = "John";
var age = 40;
var designations = "Full Stack Developer";
var workingHours = 8;

// ES5
var person = {
  name: name,
  age: age,
  designation: designation,
  workingHours: workingHours,
};

// ES6
const person = { name, age, designation, workingHours };
Enter fullscreen mode Exit fullscreen mode

You will experience many features and flexibility in ES6 syntax

Don't Forget key Prop With map in JSX

Always assign a unique value to the key prop to every JSX element while mapping from an array. Read official docs for better understanding

const students = [{id: 1, name: 'Bilal'}, {id: 2, name: 'Haris'}];

// in return function of component
<ul>
  {students.map(({id, name}) => (
    <li key={id}>{name}</li>
  ))}
</ul>;
Enter fullscreen mode Exit fullscreen mode

Component Name Should be in PascalCase

const helloText = () => <div>Hello</div>; // wrong

const HelloText = () => <div>Hello</div>; // correct
Enter fullscreen mode Exit fullscreen mode

Variable & Function Names Should be in camelCase

const working_hours = 10; // bad approach

const workingHours = 10; // good approach

const get_sum = (a, b) => a + b; // bad approach

const getSum = (a, b) => a + b; // good approach
Enter fullscreen mode Exit fullscreen mode

ID & Class Names Should be in kebab-case

<!--bad approach-->
<div className="hello_word" id="hello_world">Hello World</div>

<!--good approach -->
<div className="hello-word" id="hello-world">Hello World</div>
Enter fullscreen mode Exit fullscreen mode

Always Check null & undefined for Objects & Arrays

Neglecting null and undefined in the case of objects & arrays can lead to errors.

So, always check for them in your code

const person = {
  name: "Haris",
  city: "Lahore",
};
console.log("Age", person.age); // error
console.log("Age", person.age ? person.age : 20); // correct
console.log("Age", person.age ?? 20); //correct

const oddNumbers = undefined;
console.log(oddNumbers.length); // error
console.log(oddNumbers.length ? oddNumbers.length : "Array is undefined"); // correct
console.log(oddNumbers.length ?? "Array is undefined"); // correct
Enter fullscreen mode Exit fullscreen mode

Avoid Inline Styling

Inline styling makes your JSX code messy. It is good to use classes & ids for styling in a separate .css file

const text = <div style={{ fontWeight: "bold" }}>Happy Learing!</div>; // bad approach

const text = <div className="learning-text">Happy Learing!</div>; // good approach
Enter fullscreen mode Exit fullscreen mode

in .css file:

.learning-text {
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

Avoid DOM Manipulation

Try to use React state instead of DOM manipulation as

Bad approach

<div id="error-msg">Please enter a valid value</div>
Enter fullscreen mode Exit fullscreen mode
document.getElementById("error-msg").visibility = visible;
Enter fullscreen mode Exit fullscreen mode

Good approach

const [isValid, setIsValid] = useState(false);

<div hidden={isValid}>Please enter a valid value</div>;
Enter fullscreen mode Exit fullscreen mode

Set isValid false or true where you have logic of validating a value

Always Remove Every Event Listener in useEffect

Don't forget to write cleanup function in useEffect to remove event listener you added before

const printHello = () => console.log("HELLO");
useEffect(() => {
  document.addEventListener("click", printHello);
  return () => document.removeEventListener("click", printHello);
});
Enter fullscreen mode Exit fullscreen mode

Avoid Repetition, Use Generic Components

It is the best thing to make your code cleaner. Write a generic component for similar group of elements and render them on the basis of props
passed to it

const Input=(props)=>{
  const [inputValue, setInputValue]=useState('');
  return(
    <label>{props.thing}</label>
    <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)} />
  )
}
Enter fullscreen mode Exit fullscreen mode

In other component you can use Input component as

<div>
  <Input thing="First Name" />
  <Input thing="Second Name" />
</div>
Enter fullscreen mode Exit fullscreen mode

Don’t Throw Your Files Randomly

Keep the related files in the same folder instead of making files in a single folder.

For example, if you want to create a navbar in React then you should create a folder and place .js & .css files related to the navbar in it

Functional Components Are Recommended

If you want to render some elements and don't need to use state then use functional components instead of class components because functional components are easy to use.

Moreover, if you have an idea of React Hooks, then with functional components you can easily play with the state too.

Create a Habit of Writing Helper Functions

Sometimes you need a utility at more than one time across your React App.

To deal with this scenario efficiently, Write a helper function in a separated file named helper-functions.js, import wherever you want to use it and call that function in it.

Use Ternary Operator Instead of if/else if Statements

Using if/else if statements makes your code bulky. Instead try to use ternary operator where possible to make code simpler & cleaner

// Bad approach
if (name === "Ali") {
  return 1;
} else if (name === "Bilal") {
  return 2;
} else {
  return 3;
}

// Good approach
name === "Ali" ? 1 : name === "Bilal" ? 2 : 3;
Enter fullscreen mode Exit fullscreen mode

Make index.js File Name to Minimize Importing Complexity

If you have a file named index.js in a directory named actions and you want to import action from it in your component, your import would be like this

import { actionName } from "src/redux/actions";
Enter fullscreen mode Exit fullscreen mode

actions directory path is explained in the above import . Here you don't need to mention index.js after actions like this

import { actionName } from "src/redux/actions/index";
Enter fullscreen mode Exit fullscreen mode

Destructuring of Props

If you want to get rid of writing an object name again and again to access its properties, then destructuring of that object is the best solution for you.
Suppose your component is receiving some values like name, age and designation as props

// Bad approach
const Details = (props) => {
  return (
    <div>
      <p>{props.name}</p>
      <p>{props.age}</p>
      <p>{props.designation}</p>
    </div>
  );
};

// Good approach
const Details = ({ name, age, designation }) => {
  return (
    <div>
      <p>{name}</p>
      <p>{age}</p>
      <p>{designation}</p>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Don't Try to Access Modified State Variable in the Same Function

In a function, if you are assigning a value to a state variable then you won't be able to access that assigned value even after it has been assigned in that function

const Message = () => {
  const [message, setMessage] = useState("Hello World");
  const changeMessage = (messageText) => {
    setMessage("Happy Learning");
    console.log(message); // It will print Hello World on console
  };

  return <div>{message}</div>;
};
Enter fullscreen mode Exit fullscreen mode

Use === Operator instead of ==

While comparing two values, strictly checking both values and their data types is a good practice.

"2" == 2 ? true : false; // true
"2" === 2 ? true : false; // false
Enter fullscreen mode Exit fullscreen mode

Now get your hands dirty with these best coding practices in React!

Top comments (46)

Collapse
 
thisurathenuka profile image
Thisura Thenuka • Edited on

Great article Hafiz. I noticed one little doubtful practice regarding the nested ternaries. Some linters actually don't suggest this method due its lack of readability.

Non-compliant code

function getReadableStatus(job) {
  return job.isRunning() ? "Running" : job.hasErrors() ? "Failed" : "Succeeded ";  // Noncompliant
}
Enter fullscreen mode Exit fullscreen mode

Compliant Solution

function getReadableStatus(job) {
  if (job.isRunning()) {
    return "Running";
  }
  return job.hasErrors() ? "Failed" : "Succeeded";
}
Enter fullscreen mode Exit fullscreen mode

Read more at rules.sonarsource.com/javascript/R...

Collapse
 
gweaths profile image
Grant

Good article for those new to React. I disagree with the ternary point (like many others). Ternary is great when checking only 1 condition where the outcome is say

const saving = userIsEmployee ? 50 : 10.

With multiple conditions or more than one the ternary can become unreadable and an if else would be more appropriate. Or my preferred method would be a switch case.

Depending on the number of options , or condition could potentially even utilise a object literal lookup.

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Agreed

Collapse
 
jareechang profile image
Jerry • Edited on

Great tips!

Btw, if you are using Typescript or support modern browser, you can use optional chaining.

Here is what that would look like:

const oddNumbers = undefined;

console.log(oddNumbers?.length ? oddNumbers.length : "Array is undefined"); // correct
console.log(oddNumbers?.length ?? "Array is undefined")
Enter fullscreen mode Exit fullscreen mode

Otherwise, it would error out.

Collapse
 
brense profile image
Rense Bakker

Great article. I'm always happy when people write about best practices, even if I disagree with some. The inline css for example i actually prefer it because it keeps me from having to go to another file if im changing the appearance of something. There are great libraries out there that help to keep the css in js more clean, like mui/emotion for example.

Collapse
 
scottbeeker profile image
Scott Beeker

Great Stuff!!
If anyone want's to follow each other on github here's my handle
github.com/dangolbeeker

Collapse
 
monotype profile image
Pavlo

Followed. Please follow back to mine: github.com/its-monotype

Collapse
 
amoabakelvin profile image
Kelvin Amoaba • Edited on

Follwed. Here's mine github.com/AmoabaKelvin

Collapse
 
scottbeeker profile image
Scott Beeker

Followed back!

Collapse
 
scoobytux profile image
Tu Le

Followed. Please follow back to mine:
github.com/scoobytux

Collapse
 
edgarslv profile image
EdgarsLv • Edited on

Always Check null & undefined for Objects & Arrays

You will get TypeError: cannot Read properties of undefined reading 'length' and cannot Read properties of undefined reading name in all 6 cases.

You have to do: oddNumbers?.length with question mark.
Same with: person?.name.

Collapse
 
anikkdev profile image
Anik K Dev

One of the best article that I came across. thank you.

Collapse
 
mbthales profile image
Thales Maia

Thanks for the article, but, i didn't understand this: "In a function, if you are assigning a value to a state variable then you won't be able to access that assigned value even after it has been assigned in that function". Could you explain?

Collapse
 
vcnsiqueira profile image
Vinícius Siqueira

In React the useState hook is asynchronous, so if you try to access the state just after it has changed in a direct way, you don't have any guarantee this will show you the actual value or the previous value. It you need to access the new value, it is a good idea to use a new value (let's say newValue), then change the state using the setMessage (using the same hook as the example) and than calling the newValue to console, for instance.

Collapse
 
richieaiello profile image
Richard Aiello

I believe you would need to place the console.log inside the useEffect hook and include the state variable inside the useEffect's dependency array. Like Hafiz said state change in React is asynchronous, so the useEffect would be able to display the new state after the component renders.

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Because state change in React is asynchronous so we can't get modified state immediately.

Collapse
 
zesta profile image
Mwenedata Apotre

Happy to see that I follow almost all of them, except I usually use inline styles due to the use Tailwind CSS. Great Article!!

Collapse
 
hubedav profile image
Dave

Definitely bookmarking this for future reference!

That said, the ternary operator over if/else I would recommend the opposite. Nesting ternary operations/statements should generally be avoided for readability reasons. The operator certainly has it's uses, but I personally feel like that's not one of them.
(just my 2₵, FWIW)

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Sure. ternary operator should be used whenever it is needed. For more complex conditions or multiline code to be executed after some condition, we should use if/else in this case.

Collapse
 
amn3s1a2018 profile image
Amn3s1a2018

You should add one more question mark, like:
console.log(oddNumbers❓.length ?? "Array is undefined");
I suggest to use TypeScript instead, in vscode with type checking, it's virtually impossible to make similar mistakes.

Collapse
 
_haris_shah profile image
Haris Shah

Thank you for sharing 🙌
It would be highly appreciated if you could write an article about react-redux as well.

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal
Collapse
 
tealover418 profile image
Stijn de Ligt

Would very much recommend adding typescript to this list. React support for it is great and it prevents a lot of beginner level bugs.

Collapse
 
arsalannury profile image
ArsalanNury

hi Hafiz thank you for sharing .
there is just one thing , i think ternary operator is not good for every condition statement. correct me if i'm incorrect

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Try to use it whenever possible instead of if/else statements because ternary operator makes the code shorter

Collapse
 
hafeez1042 profile image
Hafeez Hamza

Yes it make the code shorter, but it become hard to read if we use lots of nested ternary operations

Also i have seen some developers using ternary operations for calling a function or doing an action, as a best practice I suggest to use ternary only for returning a value or assigning to a variable.

Eg.
return name === "Ali" ? 1 : (name === "Bilal" ? 2 : 3);
const value = name === "Ali" ? 1 : (name === "Bilal" ? 2 : 3);

Collapse
 
vinnieolamide profile image
Vincent

Thanks for the article.

Some comments have been hidden by the post's author - find out more

Stop sifting through your feed.

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.