React Clean code Best Practices

Codylillyw
4 min readFeb 23, 2023

--

One important aspect of every PR you make is to make sure it is clean. In addition to your companies own best practices consider this checklist and if you have questions review the explanation below it.

React PR commit clean code checklist

□ Touch only files relevant to PR purpose

□ Check variable names for clarity. Ask someone else to interpret it.

□ Review components for any time you have to function hop to understand

□ Think about different ways the problem could be solved

□ Few to no comments

□ No console logs

□ Search for duplicate code and determine if it can be written as a single purpose function

□ Avoid making changes to reused components

□ Test all pages that use components

Meaningful names

Don’t leave names bad so you can find them later. Fix them as soon as you think of a better name.

React is unopinionated about how you name files and folders. One convention is to have components, pages, and helpers folders. jsx components start with capitals like TestComponent.jsx. Helps follow camel case. This is just one way to handle this though.

Pronounceable — Avoid abbreviations or acronyms as they can easily be misunderstood even if the meaning is obvious to you. It is better just to spell it out.

Searchable — Avoid using magic numbers by giving them variable names. Give names that you can easily search for.

Direct — Avoid using names to be funny requiring interpretation.

One word per concept — Don't use get and fetch verbs for functions that both obtain information from the API. Have a standard and correct it when the standard is broken. Also avoid using the same verb if they have different meanings in the context. You can group related ideas using a prefix when there is no other way to group them.

Problem/Solution domain — Use design patterns, math, and algorithms in the name when relevant and commonly understood by your team. If you cannot identify it by the solution use the problem.

Functions

Balance component size and reuse— There is a balance between kindergarten components and 5000 line files. Create Separate pages when there are separate routes. Reusability is important but should not come at the cost of overhead where it is so generalized you no longer understand what the code is doing.

Avoid prop drilling — Prop drilling leads to having to change many places to small changes and search for what the prop means.

Use only required hooks — Do not leave stale code like useRef when the ref is no longer used or useNavigate when you determined to use a link instead.

Do one thing — A function should have a single purpose such as fetching from one endpoint for a useEffect.

Minimal arguments — avoid returning objects as since JavaScript is not typed you will not know what is expected to be in the object. Use as few arguments as possible.

  • No arguments: Providing abstraction value only
  • Use Monadic when: Components use props and as such will always only have the Props object, asking a question, transforming and returning
  • On anything larger than one argument seek for the ordering to be natural or not important.

Comments

Comments should be avoided in all cases if possible. Legal information should be kept in the readme if you really need it in the code.

Self-describing Code

Instead of using a comment make the code self explanatory through naming and minimal abstractions. Only use abstractions when it adds readability without needing to jump to the definition to understand what is happening.

//TODO — Rather than adding a todo comment, solve the problem outright

// This code calculates the cost with tax — Let the code speak for itself by using variable names like tax, totalBeforeTax and totalAfterTax.

//Returns a set of address information — You can resolve this by combining the information in a object, array, or appending a prefix to related information.

Historical Comments

//code here — Commented out code should just be removed. Use git controls if you really need it back

console.log — Do not leave console logs. They add to the confusion and are unprofessional. Rewrite them.

//Written by Dave — Git commits store this information. You can use gitlens to see who wrote each line if needed.

Component Formatting

  • Very first line — Destructure Props (If there)
  • Destructure redux state — (If there)
  • Initialize State Variables — (If there)
  • Create Refs — (If there)
  • Initialize hooks ( useDispatch)
  • Write all useEffects
  • Create const/var/let specific to Component
  • Call functions — If there
  • Render — Least amount of elements, least amount of classes, least amount of need to look outside the component. Strip everything back to prove elements and classes are needed.

The order of imports and props is only preference. In my opinion, this does not improve readability. If you use prettier which automatically sets the order then than may help with consistancy here.

Error Handling

Handle null and undefined — You can use try catch, optional chaining, and Error Boundaries to work with errors. You should make sure not to pass or accept null values.

Avoid vague return codes — The backend should give the appropriate error codes and handle formatting ie if it needs to be all capital in the case the frontend fails to do so or at least give some warning. It should not share anything private that would risk security. It should only send what is necessary.

Test how things work before you use them. Wrap them if needed.

References

React Worst Practices — The Beginning | by राहुल मिश्रा | Medium

dev-marko/clean-code-book: Here is the PDF version of the book “Clean Code” by Robert C. Martin. A must read books for upcoming (and senior) developers who want to learn how to write masterpieces and not just lines of code :) (github.com)

--

--

Codylillyw
Codylillyw

Written by Codylillyw

I am a Software engineering student in my senior year with most of my experience in web development and related technology.

No responses yet