Đối với các dự án phần mềm nói chung và các dự án React nói riêng, việc viết và giữ cho code clean là điều tối quan trọng. Nó ảnh hưởng tới sự mở rộng, bảo trì của dự án sau này cũng như tác động trực tiếp tới tinh thần của lập trình viên được bàn giao dự án về sau.
Việc giữ cho dự án clean cần rất nhiều nỗ lực cũng như kinh nghiệm, quá trình clean code cũng giống như việc dọn dẹp nhà cửa vậy, sau một thời gian sẽ luôn phát sinh bụi bẩn trong ngôi nhà tên Project. Việc dọn dẹp vì thế cũng phải được lặp lại suốt vòng đời của dự án. Công việc dọn dẹp sẽ nhẹ nhàng hơn phần nào nếu bạn thực hiện một số phương pháp, quy tắc giúp code clean hơn ngay từ đầu.
Cùng dạo qua một số tip nho nhỏ giúp cho giúp cho dự án React của bạn clean hơn “một chút”.
1. JSX ShortHand
Dùng JSX shorthand để truyền các biến boolean
Thường thấy
return (
<Navbar showTitle={true} />
);
Tốt hơn
return(
<Navbar showTitle />
)
2. Toán tử bậc 3
Thường thấy
const { role } = user;
if(role === ADMIN) {
return <AdminUser />
}else{
return <NormalUser />
}
Tốt hơn
const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />
3. Tận dụng key của object
Thường thấy
const {role} = user
switch(role){
case ADMIN:
return <AdminUser />
case EMPLOYEE:
return <EmployeeUser />
case USER:
return <NormalUser />
}
Tốt hơn
const {role} = user
const components = {
ADMIN: AdminUser,
EMPLOYEE: EmployeeUser,
USER: NormalUser
};
const Component = components[role];
return <Componenent />;
4. Các mảnh phản ứng
Sử dụng Fragment
thay cho div
nếu có thể. Nó giữ cho mã sạch sẽ và cũng có lợi cho hiệu suất vì có ít nút hơn được tạo trong DOM ảo.
Thường thấy
return (
<div>
<Component1 />
<Component2 />
<Component3 />
</div>
)
Tốt hơn
return (
<>
<Component1 />
<Component2 />
<Component3 />
</>
)
5. Không thể cài đặt chức năng bên trong đầu ra
Thường thấy
return (
<button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>
This is a bad example
</button>
)
Tốt hơn
const submitData = () => dispatch(ACTION_TO_SEND_DATA)
return (
<button onClick={submitData}>
This is a good example
</button>
)
6. Sử dụng bản ghi nhớ
React.PureComponent
và Memo
có thể cải thiện đáng kể hiệu suất của ứng dụng của bạn. Chúng giúp chúng ta tránh việc hiển thị không cần thiết.
Thường thấy
import React, { useState } from "react";
export const TestMemo = () => {
const [userName, setUserName] = useState("faisal");
const [count, setCount] = useState(0);
const increment = () => setCount((count) => count + 1);
return (
<>
<ChildrenComponent userName={userName} />
<button onClick={increment}> Increment </button>
</>
);
};
const ChildrenComponent =({ userName }) => {
console.log("rendered", userName);
return <div> {userName} </div>;
};
Mặc dù thành phần con chỉ hiển thị một lần vì giá trị của count không liên quan gì đến ChildComponent
. Tuy nhiên, nó sẽ hiển thị mỗi khi bạn nhấp vào nút.

Tốt hơn
import React ,{useState} from "react";
const ChildrenComponent = React.memo(({userName}) => {
console.log('rendered')
return <div> {userName}</div>
})
7. Phá hủy đối tượng
Thường thấy
return (
<>
<div> {user.name} </div>
<div> {user.age} </div>
<div> {user.profession} </div>
</>
)
Tốt hơn
const { name, age, profession } = user;
return (
<>
<div> {name} </div>
<div> {age} </div>
<div> {profession} </div>
</>
)
8. Chuỗi đạo cụ Truyền
Thường thấy
return(
<Navbar title={"My Special App"} />
)
Tốt hơn
return(
<Navbar title="My Special App" />
)
9. Không nên kết nối chuỗi để tạo chuỗi lớn
Thường thấy
const userDetails = user.name + "'s profession is" + user.proffession
return (
<div> {userDetails} </div>
)
Tốt hơn
const userDetails = `${user.name}'s profession is ${user.proffession}`
return (
<div> {userDetails} </div>
)
10. Sắp xếp nhập khẩu
Sắp xếp mọi import theo một thứ tự nhất định. Nó cải thiện khả năng đọc code.
Thường thấy
import React from 'react';
import ErrorImg from '../../assets/images/error.png';
import styled from 'styled-components/native';
import colors from '../../styles/colors';
import { PropTypes } from 'prop-types';
Tốt hơn
Nguyên tắc chung là giữ thứ tự import như sau:
- Built-in
- External
- Internal
import React from 'react';
import { PropTypes } from 'prop-types';
import styled from 'styled-components/native';
import ErrorImg from '../../assets/images/error.png';
import colors from '../../styles/colors';
11. Sử dụng tính năng trả tiền của JavaScript
Thường thấy
const add = (a, b) => {
return a + b;
}
Tốt hơn
const add = (a, b) => a + b;
12. Đặt thành phần tên
Luôn sử dụng quy tắc PascalCase cho các component và camelCase cho các instance.
Thường thấy
import reservationCard from './ReservationCard';
const ReservationItem = <ReservationCard />;
Tốt hơn
import ReservationCard from './ReservationCard';
const reservationItem = <ReservationCard />;
13. Đặt tên riêng cho prop
Không sử dụng tên prop của thành phần DOM để chuyển props giữa component
Thường thấy
<MyComponent style="dark" />
<MyComponent className="dark" />
Tốt hơn
<MyComponent variant="fancy" />
14. Dấu ngoặc
Sử dụng dấu ngoặc kép cho thuộc tính JSX và dấu ngoặc đơn cho tất cả các JS khác.
Thường thấy
<Foo bar='bar' />
<Foo style={{ left: "20px" }} />
Tốt hơn
<Foo bar="bar" />
<Foo style={{ left: '20px' }} />
15. Đặt tên prop
Thường thấy
<Component
UserName="hello"
phone_number={12345678}
/>
Tốt hơn
<MyComponent
userName="hello"
phoneNumber={12345678}
Component={SomeComponent}
/>
16. Đặt JSX trong ngoặc đơn
Nếu component của bạn nhiều hơn một dòng, hãy luôn đặt nó trong dấu ngoặc đơn.
Thường thấy
return <MyComponent variant="long">
<MyChild />
</MyComponent>;
Tốt hơn
return (
<MyComponent variant="long">
<MyChild />
</MyComponent>
);
17. Tag Closed
Thường thấy
<SomeComponent variant="stuff"></SomeComponent>
Tốt hơn
<SomeComponent variant="stuff" />
18. Dấu gạch dưới trong phương thức tên
Thường thấy
const _onClickHandler = () => {
// do stuff
}
Tốt hơn
const onClickHandler = () => {
// do stuff
}
19. Thuộc tính alt
Luôn đặt alt trong thẻ <img > của bạn
Thường thấy
<img src="hello.jpg" />
<img src="hello.jpg" alt="Picture of me rowing a boat" />
Tốt hơn
<img src="hello.jpg" alt="Me waving hello" />