Welcome to the first part of my blog series, "React Best Practices in 2023." In this blog, we will delve into the crucial topic of naming conventions and how they serve as the foundation of clean and maintainable code in React.
Naming conventions play a vital role in improving code readability, maintainability, organization, and communication. They help create a cohesive and structured codebase that is easier to work with, reduces errors, and promotes collaboration among developers.
In this part, we will focus specifically on naming conventions in React. We will explore the recommended approaches for naming components, variables, functions, and other identifiers within your React projects. You'll gain insights into the popular conventions such as PascalCase, camelCase, kebab-case and SCREAMING_SNAKE_CASE, and understand when and where to apply them.
We will also discuss the benefits of meaningful and descriptive names that accurately reflect the purpose and functionality of the elements in your code.
Pascal Case
Pascal Case typically refers to the convention of writing compound words in which the first letter of each word is capitalized and there are no spaces or punctuation marks between the words.
In React, we can use pascal case for below elements:
1. React Component
// React Component
const Todo = () => {
//...
}
2. CSS Class Names
// CSS Class Names
Todo.css
Todo.scss
Todo.module.scss
3. Enumerations
// Enums
const RequestType = {
//...
}
Camel Case
Camel case refers to the convention of writing compound words or phrases where each word begins with a capital letter except the first word, which starts with a lowercase letter.
In React, we can use camel case for below elements:
1. Variable Names
// Variable Name
const userName = "sathishskdev";
2. Function Names
// Function Name
const getFullName = (firstName, lastName) => {
return `${firstName} ${lastName}`;
}
3. Object Properties
// Object Properties
const user = {
userName: "sathishskdev",
firstName: "Sathish",
lastName: "Kumar"
}
4. CSS Module Class Names
// CSS Module Class Names
.headerContainer {
display: "flex";
}
5. Custom Hooks
const useTodo = () => {
//...
}
6. Higher Order Component
const withTimer = () => {
//...
}
Kebab Case
Kebab case refers to the convention of writing compound words in lowercase letters and separating them with hyphens("-").
In React, we can use kebab case for below elements:
1. CSS Class Names
// CSS Class Names
header-container {
display: "flex";
}
<div className="header-container">
//...
</div>
2. Folder Names
// Folder Names
src
todo-list // Folder name
TodoList.jsx
TodoList.module.scss
todo-item // Folder name
TodoItem.jsx
SCREAMING_SNAKE_CASE
SCREAMING_SNAKE_CASE refers to the convention of writing compound words or phrases in uppercase letters, with words separated by underscores ("_").
1. Constants
// Constants
const BASE_PATH = "https://domain.services/api";
2. Enumeration Properties
// Enumeration Properties
const RequestType = { // Name in Pascal Case
// Properties in Screaming Snake Case
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE',
};
3. Global Variables
// Global Variables
const ENVIRONMENT = 'PRODUCTION';
const PI = 3.14159;
Higher-Order Component Naming Convention
Here are best practices for naming Higher-Order Component:
1. Use "with" as Prefix
Common convention is to use the prefix "with" followed by the functionality or purpose of the HOC.
2. Use "Original Component" as Suffix
Include the original component name in the HOC's name to indicate the component it is enhancing or wrapping
// HOC: name have "with" as Prefix
// "Filter" is add as Suffix which is original component
const withFilter = () => {
//...
}
// Usage of the HOC
const Filter = withFilter(/*Component Name*/);
Custom Hooks Naming Convention
Here are best practices for naming custom hooks:
1. Use "use" as Prefix
Common convention is to use the prefix "use" followed by the functionality or purpose of the Custom Hooks.
2. Use "Behaviour of hook" as Suffix
Name the custom hooks that accurately describes the purpose or behaviour of the custom hook.
// Custom Hook: useTimer
// name have "use" as Prefix
// "Timer" is add as Suffix which is behaviour of hook
const useTimer = (initialTime) => {
// ... hook implementation
};
// Usage of the custom hook
const { time, start, stop, reset } = useTimer(60);
Use more descriptive and specific names
It's important to avoid using generic or unclear names for your components, variables, or functions.
Let's take an example to illustrate this:
// ❌ Pitfalls to Avoid
const MyComponent = () => {
// What kind of component is this?
const data = getData()
// What kind of data is this?
const onClick = () => {
// What does it do?
}
//...
}
In the above example, The component name, variable name "data" and the function name "onClick" are generic and don't convey their specific purpose or context.
To improve clarity and maintainability, it's recommended to use more descriptive and specific names.
Here's an best practice:
// ✅ Best Practice
const ProductDetails = () => {
const productInfo = fetchProductInfo();
// Fetches detailed product information
const addProductToCart = () => {
// Add the product to the shopping cart
};
//...
}
In the improved example, the component is renamed to "ProductDetails", which clearly indicates its purpose. The variable name "productInfo" conveys that it holds detailed information about a product. The function name "addProductToCart" describes its action of adding the product to the shopping cart.
By using descriptive and meaningful names, it becomes easier for other developers (including yourself) to understand and maintain the code in the long run.
Choosing Singular or Plural Naming
The decision to use singular or plural names for various elements, such as components, variable and functions, can significantly impact code clarity.
Let's take an example:
// ✅ Best Practice
const fetchConversation = () => {
// Fetch single conversation.
}
const fetchConversations = () => {
// Fetch multiple conversations.
}
// Use singular name for a single conversation
const conversation = { /*Conversation Details*/ }
// Use plural name for multiple conversation
const conversations = [
{ /*Conversation Details*/ },
{ /*Conversation Details*/ }
]
By aligning the singular or plural form of component, function and variable names with their intended purpose, we improve code readability and facilitate better understanding for other developers working on the codebase.
Avoid Excessive Abbreviations
Here's an example that demonstrates the importance of avoiding excessive abbreviations in code:
// ❌ Bad example
// Excessive abbreviation
const selUsr = {
usrId: '1',
usrNm: 'Sathish Kumar',
usrEmail: 'sathish@domain.com',
};
// Usage
selUsr.usrId
In the above example, the object selUsr
contains selected user information with abbreviated property names like usrId
, usrNm
, and usrEmail
. While this code may be functional, it lacks clarity and can cause confusion for other developers who need to work with this object and property.
Here's an best practice:
// ✅ Best Practice
// Descriptive object and property names
const selectedUser = {
userId: 1,
userName: 'Sathish Kumar',
userEmail: 'sathish@domain.com',
}
// Usage
selectedUser.userId
In this example, the property names userId, userName, and userEmail are more descriptive, providing a clearer understanding of the data being used. This makes the code easier to read, maintain, and collaborate on, contributing to better overall code quality.
That concludes our exploration of naming conventions in React.js. By following these best practices, you are well-equipped to create clean, readable, and maintainable code in your React projects.
Remember, choosing meaningful and descriptive names for your variables, functions, components, and other elements is essential for enhancing code clarity and improving collaboration among developers. Consistency in naming conventions throughout your project will make your codebase more organized and easier to understand.
In the next part of our series, we will delve into the critical topic of folder structure in React. We'll discuss how to organize your project's files and directories effectively, and how to implement a modular approach that promotes code reusability and maintainability.
Stay tuned for next post!
Happy coding!😊👩💻👨💻
Top comments (9)
Thanks, Sathish, Your advice resonated with me, and I'm excited to apply it to enhance my code. Keep up the great work! 👍💻
Thank you for your comment! It's always fulfilling to receive such positive feedback.
Great post and good convention for naming everything in React, thanks
Thank you for your comment!
Very informative
Thank you for your comment!
you forgot to mention about file naming conventions for react components and that is where most of the developers differ, some use kebab well others pascal.
I'm using pascal naming convention because i have an extension in vscode that give me a basic skeleton for the component and which by default uses the file name directly as component name and yeah i don't want to modify each time the component name to be pascal if i make the file name kebab.
Great Post
I believe that in the selected User object the properties also don't need the user prefix, which makes them redundant