Why Follow React Coding Best Practices?
Writing code to create apps isn't just enough; the code should be as clean and maintainable as your app. Before jumping into the good practices to follow, it's essential to realize the reasons behind the same. It becomes crucial for you to understand coding conventions because of the following reasons:
- As a developer, you shall understand that writing code to build apps is not enough, but the code should also be Reliable, Scalable, and Maintainable. Generally, 40% - 80% of the total cost of software is spent on its maintenance.
- Readability is the priority. Any software is seldom fully supported by one single developer; There is a whole team or group of people working on it. Furthermore, new developers always join the project team. Thus, maintaining coding standards improves the product's readability that lets developers easily understand the codebase even faster.
- Like any product, the software must be well-packaged and clean. Following best coding practices helps you write clean code throughout the codebase by ensuring consistency.
Starting with React Best Practices
There's basically no defined structure, but you should have a style to follow throughout the codebase. Thus, this section explains how you can structure your codebase for medium to large-sized apps.
Put all your imports in order at the very top of the code file. You shall ideally prioritize as follows:
import * as<>
import ./<some file>
Make sure all your imports statements are on new lines, as this will make your imports clean and easy to understand for all the components, third-party libraries, etc.
index.jsfor each folder to export so that all the imports are referenced on the
index.jsfile, and you don't have to write import statements again and again for every file.
It's easy to get confused about whether to use double quotes (" ") or single quotes (' ') while working with React. The simple answer is:
maintain consistencywhatever you're using.
Also, consider that you use double quotes (" ") for
JSXattributes and single quotes (' ') for the
JScode (Follow the standard way or maintain consistency).
- Most of the time, beginners merge two-three components inside a single file and play around with that. However, that's not a good practice to follow. Dividing the whole app into components and then working on it on a separate file is a good practice to maintain clean code.
- Do you sometimes use CSS styles with JSX? But it's a bad practice. Always make
classNamesfor each element and put all the styling under respective CSS files only.
- Your filenames should always have consistent casing and extension. Either use
.jsxas explained in code structure for extensions. And
- In React, name your file the same as the React component inside that file i.e. without a hyphen in the filename. For example:
- Not only filename but also make sure that your
variables/functions/modulesfilenames are consistent with cases.
- Use well-descriptive names for
variables/functions/modules/Actions, keeping in mind that it is application-specific so that even a third party or new developer can easily understand you code.
_onClickSubmit() → ❌
- When making reducer functions, write
domain/eventNames. For example:
INCREMENT(in CAPITALS) as this matches the typical conventions in most programming languges for declaring the constant values.
- Talking about
casesin a React component, use
PascalCasefor the same — and for their instances, use
camelCase. For example:-
const loginForm = <LoginForm />; import LoginForm from './loginForm';
Files and Folders
- Your app's directory structure shall be as follows:
└── /src ├── /assets - Contains static assets such as images, svgs, company logo etc. ├── /components - reusable components like navigation bar, buttons, forms ├── /services - JavaSript modules ├── /store - redux store ├── /utils - utilities, helpers, constants. ├── /views/pages - majority of the app pages would be here ├── index.js └── App.js
- Each component folder should have its respective files grouped under the same. It maintains the hierarchy throughout the codebase. The necessary files include:
- Play the game of HOOKS by following all its rules. You can read more about the rules here. Either manually follow these rules or use an ESLint plugin called
eslint-plugin-react-hookswhich enforces these rules. So, add these rules while working on any project
console. logs— unless you have strong motivation why you would like it.
- Avoid multiple
if-else blocks. Instead, use
ternary— best for clean code practice
- Remove all
commented-out codes. The biggest motivation for writing comments is the bad code that you write. It would be good to spend more time writing descriptive functions, methods, and filenames that are self-explanatory.
Testsfor each component. It's a good practice to write test cases for each component developed as it reduces the chances of getting errors when deployed. You can check all the possible scenarios through unit testing — and for that, some of the most commonly used React test frameworks you can use are
Good Commenting Practices
- Use comments to explain why you did something, not how you did it. If you find yourself explaining how you did something, then it's time to make your code self-explanatory.
- Another point is not to write comments that are obvious and redundant — for example:
// Prints out the sum of two numbers console.log(sum);
- Write comments that are legal, informative, explanatory of intent, and offer clarification,
- Always destructure your props. Destructuring your props helps make your code cleaner and more maintainable. It also makes assigning object properties to variables feels like much less of a chore.
- Know where to use spread/rest operators. You shall read about it before actually using it.
- Try using
optional chainingif possible.
constlets you check that a variable should always stay constant.
letindicates that the values of the variables can be changed.
- Start preferring
arrow functions(= >) for more cleaner code. Arrow functions allow simplifying your code to a single line.
- Always ensure that your app is responsive.
- Your app should contain a proper
README.mdfile that clearly details or explains your app. Clearly mention the features, functionalities, contributions guidelines, installation process, guide, etc.
- Do check that your app runs without any errors.
EsLintthroughout your codebase and other automation tools so that most of the best practices are maintained automatically for you.
- Consolidate duplicate code throughout the codebase.
Please note that I haven't talked about automation extension and tools that can help you maintain most of the best practices easily without looking into separately. But, I wanted to bring this into consideration. Anyhow, you can use extensions like
PLOP etc., to maintain your codebase efficiently.
These are the best practices that I've learned practically over time by working in a team, reviewing my mates' codebase, observing open-source projects and repositories, and reading great resources, such as the offical React docs.
I hope you gained valuable insights. If you have more suggestions or practices that the React or dev community can follow, please to let us know.
Until next time, keep learning, build awesome stuff, and uplift the community.
By the way, if you want to add user registration and authentication to your React apps, you can use LoginRadius. It helps you become more efficient and focus more on the core business features of your React apps.