Clean coding practices I use in React
Your code needs to be understood by you and others who will work with you. I have been in situations where my work was only to refactor the existing code. Fixing one thing would lead to breaking other things, reading bad code took ages. A cleaner and organized code structure will also provide you with an upper edge over other candidates.
Naming and Formatting practice
- The name must be self-explanatory. The name of your function should be a verb, example, setToken, getUserInfo, calculateAge, etc.
- Camel case for class name, function, and variable names.
- Function and variables start with a lowercase letter.
- The name of your class and variable must be nouns.
- A component should start with a capitalized letter.
- Proper indentation can reveal bugs quickly and it is easier to read through the code
Adding Comments
- Avoid comment unless it adds more value such as explaining something that is not declared. A comment should explain the intent of writing the particular code logic.
- Update the comments after you refactor someone else’s code.
Functions
- A function should be small and do only one thing. Break your code down into chunks to make sure each function can only do a specific task.
- Keep arguments to the minimum
Create separate files for each component
The most important way to write cleaner React code is to get good at abstracting our code into separate React components.
This means that each file is responsible for just one component and there’s no confusion about where a component comes from if we want to reuse it across our app.
Move shared functionality into React hooks
If I wanted to perform a certain task for data across multiple components, I create a custom hook for it and reuse it in my code
Tips
- KISS (Keep it simple, stupid)
- Avoid boilerplate code that is repeated in multiple places with little to no variation
- Every piece of logic should have a single representation that is unambiguous.
I hope you find this article useful to improve your own React code to make it cleaner, easier to read, and ultimately more enjoyable to create your projects.