As a developer, we should write clean code. But before we jump into react code, what is clean code by the way?
Overview of Clean Code
Clean code is a rule to describe that the code that has been created can be easily read, understood, and maintained. Clean refers to rules and standards that make code easy to read and well followed.
Component Structure
When we talk about components in react, we can use the Single Responsibility Principle (SRP) from SOLID principles. The single Responsibility Principle in React.js means every components/function should have only one responsibility or one job to do, making it easier to read and maintain.
Example: Instead of having single components, we can separate responsible components to render UI only and other components to do data fetching
// pages/User.jsx
import React, { useEffect, useState } from 'react';
import DisplayComponent from '@/components/UserList';
const User = () => {
const [data, setData] = useState(null)
useEffect(() => {
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => setData(data))
}, [])
return <DisplayComponent data={data} />
}
export default User;
// components/UserList.jsx
import React from 'react';
const UserList = ({ data }) => {
if (!data) return <div>Loading...</div>;
return (
<div>
<h1>User:</h1>
<p>{data}</p>
</div>
);
};
export default UserList;
Naming Conventions
Naming conventions in React.js can help us improve code readability, maintainability, and collaboration.
In React.js components we use PascalCode (capitalizing the first letter of each word) for the names and also make it descriptive and meaningful.
Example :
// Component User List (Correct)
import React from 'react';
const UserList = ({ data }) => {
if (!data) return <div>Loading...</div>;
return (
<div>
<h1>User:</h1>
<p>{data}</p>
</div>
);
};
export default UserList;
// Component User List (Wrong)
import React from 'react';
const listReact = ({ data }) => {
if (!data) return <div>Loading...</div>;
return (
<div>
<h1>User:</h1>
<p>{data}</p>
</div>
);
};
export default listReact;
This implementation of the UserList
instead of listReact
defines what component it is and what should this component be doing.
Code Formatting
When we write React.js codes, especially with bigger teams, we want our project to have consistent code. So we should have code formatting for our projects.
For code formatting, we can use a document for the teams or we can use an existing code style like Airbnb.
We also can use Prettier package for code formatting. It makes our code consistent because prettier is parsing the code with custom rules that have already been created.
Conclusion
In wrapping up, it's clear that clean code is making us a better developer. Because clean code makes our code easy to read and maintain.
Hopefully, these articles can help you to understand and create code better.
Thank you!