Dark mode
Function Component ใน React
คืออะไร?
Function Component คือรูปแบบหนึ่งของการสร้างคอมโพเนนต์ใน React โดยใช้ฟังก์ชันธรรมดา (JavaScript/TypeScript function) ในการนิยาม UI และ logic ของคอมโพเนนต์นั้นๆ ซึ่งเป็นวิธีที่ได้รับความนิยมและแนะนำให้ใช้ใน React เวอร์ชันปัจจุบัน
ตัวอย่าง Function Component แบบง่าย
tsx
// MyButton.tsx
import React from "react";
type MyButtonProps = {
label: string;
};
function MyButton({ label }: MyButtonProps) {
return <button>{label}</button>;
}
export default MyButton;
หรือจะเขียนแบบ Arrow Function ก็ได้
tsx
const MyButton: React.FC<MyButtonProps> = ({ label }) => (
<button>{label}</button>
);
การรับ Props
Function Component รับ props เป็น argument แรกของ function (แบบ destructuring ได้เลย)
tsx
function Welcome({ name }: { name: string }) {
return <h1>สวัสดี {name}!</h1>;
}
เปรียบเทียบกับ Class Component
ก่อนหน้านี้ React นิยมใช้ Class Component ซึ่งมีหน้าตาดังนี้:
tsx
import React from "react";
type WelcomeProps = {
name: string;
};
class Welcome extends React.Component<WelcomeProps> {
render() {
return <h1>สวัสดี {this.props.name}!</h1>;
}
}
ความแตกต่างหลัก
ประเด็น | Function Component | Class Component |
---|---|---|
Syntax | ฟังก์ชันธรรมดา | ต้อง extends React.Component |
รับ props | ผ่าน argument | ผ่าน this.props |
State & Lifecycle | ใช้ React Hooks | ใช้ this.state, lifecycle methods |
ความกระชับ | กระชับกว่า | โค้ดยาวกว่า |
Performance | ดีกว่าเล็กน้อย (ไม่มี this) | - |
แนะนำโดย React | ✅ (ปัจจุบัน) | ❌ (เลิกแนะนำ) |
การใช้ State และ Lifecycle (React Hooks)
Function Component สามารถใช้ state และ lifecycle ได้ด้วย React Hooks เช่น useState, useEffect
tsx
import React, { useEffect, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>เพิ่ม</button>
</div>
);
}
สรุป
- ปัจจุบัน React แนะนำให้ใช้ Function Component เป็นหลัก
- โค้ดกระชับกว่า อ่านง่ายกว่า และใช้ Hooks ได้
- Class Component ยังใช้ได้ แต่ไม่แนะนำสำหรับโปรเจกต์ใหม่
Tip: ถ้าเริ่มต้นใหม่ ให้ใช้ Function Component เสมอ และใช้ TypeScript เพื่อ type safety ที่ดีขึ้น
เพิ่มเติม
- สามารถใช้ React.FC หรือไม่ใช้ก็ได้ (React แนะนำไม่ต้องใช้ FC type ในโปรเจกต์ใหม่)
- Function Component สามารถใช้กับ TypeScript ได้เต็มรูปแบบ
ดูตัวอย่างและฝึกเขียน Function Component ด้วยตนเอง จะเข้าใจข้อดีและความง่ายของรูปแบบนี้ชัดเจนขึ้น