Dark mode
React Naming Conventions
แนวทางการตั้งชื่อที่ดี ช่วยให้โค้ดอ่านง่าย ดูแลรักษาได้ในระยะยาว และลดข้อผิดพลาดในการพัฒนา
ทำไม Naming Conventions ถึงสำคัญ?
- อ่านง่าย: ใครมาอ่านโค้ดก็เข้าใจตรงกัน ไม่ต้องเดาว่าแต่ละตัวแปร/ฟังก์ชัน/ไฟล์คืออะไร
- ดูแลรักษาง่าย: เวลาต้องแก้ไขหรือขยายโค้ด จะลดโอกาสเกิด bug จากชื่อซ้ำหรือความหมายไม่ชัดเจน
- ทำงานร่วมกันได้ดี: ทีมงานหรือ open source contributor สามารถเข้าใจและ contribute ได้ง่ายขึ้น
หลักการตั้งชื่อที่ใช้บ่อย
รูปแบบ | ตัวอย่าง | ใช้กับ |
---|---|---|
PascalCase | UserProfile | Component, Class |
camelCase | userProfile | Variable, Function |
UPPER_SNAKE | MAX_USERS | Constant |
kebab-case | user-profile.js | File/Folder (บางกรณี) |
1. Component Naming
- ใช้ PascalCase
- ชื่อควรสื่อความหมายชัดเจน สั้น กระชับ
ตัวอย่างที่ดี
jsx
function UserProfile() {...}
export default UserProfile;
ตัวอย่างที่ไม่ควรทำ
jsx
function userprofile() {...} // ❌ ไม่ใช่ PascalCase
function profile() {...} // ❌ ชื่อไม่ชัดเจน
2. Hook Naming
- ขึ้นต้นด้วย use และใช้ camelCase
- ชื่อควรสื่อถึงสิ่งที่ hook ทำ
ตัวอย่างที่ดี
ts
function useAuth() {...}
function useUserProfile() {...}
ตัวอย่างที่ไม่ควรทำ
ts
function getAuth() {...} // ❌ ไม่ขึ้นต้นด้วย use
function useauth() {...} // ❌ ไม่ใช่ camelCase
3. Props Naming
- ใช้ camelCase
- ชื่อควรสื่อถึงข้อมูลหรือ action ที่ส่งเข้าไป
ตัวอย่างที่ดี
tsx
<UserProfile userName="John" onLogout={handleLogout} />;
ตัวอย่างที่ไม่ควรทำ
tsx
<UserProfile username="John" logout={handleLogout} />; // ❌ ไม่สอดคล้องกับ convention
4. State Naming
- ใช้ camelCase
- ถ้าเป็น boolean ควรขึ้นต้นด้วย is/has/can
ตัวอย่างที่ดี
ts
const [isLoading, setIsLoading] = useState(false);
const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
ตัวอย่างที่ไม่ควรทำ
ts
const [loading, setLoading] = useState(false); // ❌ ไม่บอกว่าเป็น boolean
const [User, setUser] = useState(null); // ❌ ไม่ใช่ camelCase
5. File & Folder Naming
- Component file: ใช้ PascalCase เช่น
UserProfile.tsx
- ทั่วไป: ใช้ kebab-case เช่น
user-service.ts
,api-client.ts
- Folder: ส่วนใหญ่ใช้ kebab-case หรือ PascalCase ถ้าเป็น component folder
ตัวอย่างที่ดี
/components/UserProfile.tsx
/hooks/useAuth.ts
/utils/date-utils.ts
ตัวอย่างที่ไม่ควรทำ
/components/userprofile.js // ❌ ไม่ใช่ PascalCase
/hooks/auth.js // ❌ ไม่ขึ้นต้นด้วย use
/utils/DateUtils.js // ❌ ไม่ใช่ kebab-case
6. Constant Naming
- ใช้ UPPER_SNAKE_CASE เช่น
API_URL
,MAX_RETRY
7. Test Naming
- ใช้ชื่อเดียวกับ component +
.test.tsx
เช่นUserProfile.test.tsx
8. ข้อควรระวังและเทคนิคเพิ่มเติม
- อย่าใช้ชื่อย่อหรือชื่อที่ไม่สื่อความหมาย เช่น
tmp
,data1
- ตั้งชื่อให้สอดคล้องกันทั้งโปรเจกต์ (Consistency)
- ถ้าใช้ TypeScript: interface/type ขึ้นต้นด้วย
I
หรือ PascalCase เช่นUserProfile
,IUser
- ถ้าเป็น event handler: ขึ้นต้นด้วย
handle
เช่นhandleClick
,handleSubmit
สรุป
การตั้งชื่อที่ดีใน React ไม่ใช่แค่เรื่องความสวยงาม แต่ช่วยให้โค้ดของคุณ maintain ได้ง่าย ป้องกัน bug และทำงานร่วมกับทีมได้อย่างราบรื่น ลองนำแนวทางเหล่านี้ไปปรับใช้กับโปรเจกต์ของคุณดูนะครับ!