DEV Community

Cover image for React - Best Practices

React - Best Practices

Hafiz Muhammad Bilal on November 16, 2022

While working on a React App, following these coding conventions will give you a better development experience VS Code is Highly Recommen...
Collapse
 
thisurathenuka profile image
Thisura Thenuka • Edited

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
 
grantdotdev profile image
Grant Riordan

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
 
enricoscantamburlo profile image
EnricoScantamburlo

I do find ternary operators with more than one conditions unreadable.
This is how I would have written it

if (name === "Ali") {
  return 1;
} 

if (name === "Bilal") {
  return 2;
}

 return 3;

Enter fullscreen mode Exit fullscreen mode
Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Agreed

Collapse
 
jareechang profile image
Jerry • Edited

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
 
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
Yarik Gucci

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

Collapse
 
amoabakelvin profile image
Kelvin Amoaba • Edited

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
 
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
 
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
 
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
 
anikkdev profile image
Anik K Dev

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

Collapse
 
apotre 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
 
edgarslv profile image
EdgarsLv • Edited

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
 
hariscs 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
 
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
 
cteyton profile image
Cédric Teyton

Hi Hafiz, FYI we've added your blog post on a GitHub project gathering content about best coding practices :)
github.com/promyze/best-coding-pra...

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
 
vinnietec profile image
Agboola Vincent

Thanks for the article.

Collapse
 
svijaykoushik profile image
Vijay Koushik, S. 👨🏽‍💻

Nice tips for to remember ☺️

Collapse
 
emmanuelonah profile image
Info Comment hidden by post author - thread only accessible via permalink
Emmanuel Chikwendu Onah

I have not read of this but quick thing I find wrong is:

  1. Don’t tell people not to use ==, that is a proof in inadequate Js knowledge from you
  2. Don’t tell people not to use named regular function. If I was to elaborate on this alone, it will not contend in this comment section because I will have to go from Core Js code processing to computer system and the relationship of how Core Js registers and make references to expressions and declarations like the regular named functions. But to cut the whole story short, I am not against arrow functions, but I prefer regular named functions because all JavaScript engine don’t need to struggle in providing us with vivid information about the function when things like Error occurs with the function but revers is the case with arrow function s in most cases because they all ananymous. Even ananymous regular function I don’t encourage it
Collapse
 
now_is_the_time profile image
Now is the time

These tips are very helpful for a beginner like me, definitely bookmarking this. Thanks!

Collapse
 
vishwastyagi profile image
Vishwas Tyagi

Thanks for sharing
It is good for reference.

Collapse
 
isalahyt profile image
iSalah-YT

Thank you so much 🥰🥰

Collapse
 
nicolasdanelon profile image
Nicolás Danelón

why are you giving "recommendations" but not saying the reason why?

Collapse
 
madza profile image
Madza

This is valuable, thanks a lot 👍💯✨

Collapse
 
lewisbest1 profile image
Lewis Best

Thank you for sharing, amazing article

Collapse
 
rizkytegar profile image
🎉 Rizky Tegar Pratama

great article

Collapse
 
arifpateldubaiprestonuk profile image
Arif Patel Dubai Preston UK • Edited

Thanks for this Informative article

Collapse
 
jake0011 profile image
JAKE

thanks Hafiz, not you joining dev yesterday and making a banger post same day!
great content and I learned a lot reading it.
I hope to see more of it.

Collapse
 
iamjaydev profile image
iamjaydev

Cool!

Collapse
 
devgancode profile image
Ganesh Patil

Well explain @iambilalriaz ✍🏻

Collapse
 
iambilalriaz profile image
Hafiz Muhammad Bilal

Thanks

Collapse
 
rumncode profile image
RumNCode

If you are nesting multiple if statements/ternaries, its probably best to just refactor. but i would prefer if /else if /else, or switch, over nested ternaries any day

Collapse
 
fosahadal profile image
fosware

Thanks, it's helpful!

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