React Hook คืออะไร — คู่มือโปรแกรมมิ่ง 2026 — คู่มือฉบับสมบูรณ์ 2026
React Hook คืออะไร — ความเข้าใจพื้นฐานสำหรับนักพัฒนา
React Hook คือฟังก์ชันพิเศษที่ React จัดเตรียมมาให้ เพื่อให้นักพัฒนาสามารถจัดการ state และ lifecycle ของ component ได้ง่ายขึ้น โดยไม่ต้องพึ่งพา class
component อีกต่อไป Hook ปรากฏครั้งแรกใน React 16.8 และกลายเป็นมาตรฐานที่นักพัฒนาใช้กันทั่วไป
Hook ช่วยให้ code base มีความสะอาดและเข้าใจง่ายขึ้น โดยนักพัฒนาสามารถนำ logic ที่ซ้ำซ้อนมาแยกเป็น custom hook ที่ใช้ร่วมกันได้ across components ซึ่งช่วยให้การบำรุงรักษาและทดสอบทำได้ง่ายขึ้นมาก
ผม อ.บอม ได้ใช้ React Hook มาหลายปีแล้ว ตั้งแต่เริ่มเป็น beta version จนกลายเป็น production-ready ในโปรเจกต์จริง Hook ที่ผมใช้บ่อยที่สุดคือ useState, useEffect, และ useMemo ซึ่งช่วยให้จัดการข้อมูลและ side effects ได้มีประสิทธิภาพมาก
import { useState, useEffect } from 'react';
function Counter() { const [count, setCount] = useState(0);
useEffect(() => { document.title = `Count: ${count}`; }, [count]);
return (
Count: {count}
ตัวอย่างข้างบนแสดงการใช้ useState สำหรับจัดการ state และ useEffect สำหรับ side effects เมื่อ state เปลี่ยนแปลง ซึ่งช่วยให้ component สามารถตอบสนองต่อการเปลี่ยนแปลงข้อมูลได้อย่างอัตโนมัติ
| Hook | หน้าที่หลัก | ตัวอย่างการใช้งาน |
|---|---|---|
| useState | จัดการ state ภายใน component | เก็บค่า counter, toggle, input |
| useEffect | จัดการ side effects | ดึงข้อมูล API, อัปเดต DOM, event listeners |
| useContext | เข้าถึง context จาก parent | Theme, authentication, locale |
| useRef | เก็บค่าที่เปลี่ยนแปลงได้โดยไม่ re-render | อ้างอิง DOM element, ค่าชั่วคราว |
| useMemo | memoize การคำนวณที่แพง | กรอง/จัดเรียงข้อมูล, คำนวณค่าซับซ้อน |
| Custom Hook | แยก logic ที่ใช้ซ้ำได้ | useFetch, useLocalStorage, useAuth |
Hook คือฟังก์ชันพิเศษที่ React ให้มาเพื่อใช้ state และ lifecycle ใน functional component โดยไม่ต้องเขียน class อีกต่อไป ก่อนมี Hook นักพัฒนาต้องเขียน class component ที่ซับซ้อนเพื่อจัดการ state แต่ตอนนี้แค่ import ฟังก์ชันจาก react ก็ทำได้ทันที
ตัวอย่างเช่น useState ใช้สำหรับสร้าง state ใน component, useEffect ใช้สำหรับ side effects เช่น การ fetch ข้อมูลหรือ subscription และ useContext ใช้สำหรับรับค่าจาก context
Hook ทำงานได้เฉพาะใน functional component และต้องเรียกที่ระดับ top-level ของ component เสมอ ไม่ควรเรียกใน loop, condition หรือ nested function เพราะ React อาศัยลำดับการเรียก Hook ในการจัดการ state
Hook พื้นฐานที่นักพัฒนาต้องรู้
Hook พื้นฐานมีหลายตัวที่นักพัฒนาควรศึกษาและเข้าใจอย่างลึกซึ้ง ซึ่งแต่ละตัวมีหน้าที่เฉพาะที่แตกต่างกันไป
useState ใช้สำหรับจัดการ state ภายใน component โดยรับค่าเริ่มต้นและคืนค่าเป็น array ที่ประกอบด้วย state ปัจจุบันและฟังก์ชันสำหรับอัปเดต state
useEffect ใช้สำหรับจัดการ side effects เช่น การดึงข้อมูลจาก API การสมัคร/ยกเลิก event listeners หรือการอัปเดต DOM โดยตรง
useContext ใช้สำหรับเข้าถึง context ที่ถูก provide จาก component ที่อยู่สูงกว่าใน component tree
useRef ใช้สำหรับสร้าง object ที่เก็บค่าที่สามารถเปลี่ยนแปลงได้ โดยไม่ทำให้ component re-render
useMemo ใช้สำหรับ memoize ค่าที่คำนวณได้ โดยจะคำนวณใหม่เฉพาะเมื่อ dependencies เปลี่ยนแปลง
import { useState, useEffect, useMemo } from 'react';
function ExpensiveList({ items, filter }) { const [loading, setLoading] = useState(false);
const filteredItems = useMemo(() => { return items.filter(item => item.name.includes(filter)); }, [items, filter]);
useEffect(() => { setLoading(true); fetch(`/api/items?filter=${filter}`) .then(res => res.json()) .then(data => { setItems(data); setLoading(false); }); }, [filter]);
if (loading) return
return (
- {item.name} ))}
{filteredItems.map(item => (
Hook พื้นฐานที่สำคัญที่สุดคือ useState สำหรับ state management และ useEffect สำหรับ side effects
useState รับค่าเริ่มต้นและคืนค่าเป็น array ที่มี 2 ตัวคือ state ปัจจุบันและฟังก์ชันสำหรับ update state ตัวอย่างเช่น `const [count, setCount] = useState(0)` สร้าง state ชื่อ count ที่มีค่าเริ่มต้นเป็น 0
useEffect รับ callback function และ optional dependencies array ใช้สำหรับ run code เมื่อ component mount, update หรือ unmount ตัวอย่างเช่น `useEffect(() => { console.log('mounted'); }, [])` จะ run แค่ครั้งเดียวเมื่อ component mount
Hook อื่นๆ ที่สำคัญรวมถึง useMemo สำหรับ memoize ค่าที่คำนวณแพง, useCallback สำหรับ memoize function, useRef สำหรับเก็บ mutable value, และ useContext สำหรับใช้ context
เมื่อเข้าใจหลักการพื้นฐานแล้ว เรามาดู Hook ที่สำคัญที่สุดซึ่งนักพัฒนาทุกคนควรรู้จัก useState เป็น Hook สำหรับจัดการ state ภายใน component รับค่าเริ่มต้นและคืนค่าเป็น array สองส่วน คือ ค่าปัจจุบันและฟังก์ชันสำหรับอัปเดตค่า ตัวอย่างเช่น const [count, setCount] = useState(0) จะสร้าง state ชื่อ count มีค่าเริ่มต้นเป็น 0 และฟังก์ชัน setCount สำหรับเปลี่ยนค่า
useEffect เป็น Hook สำหรับจัดการ side effects เช่น การดึงข้อมูลจาก API การสมัครรับข้อมูล หรือการแก้ไข DOM รับ callback function เป็นพารามิเตอร์แรก และ optional array เป็น dependency array ที่ควบคุมว่า effect จะทำงานเมื่อใด หากไม่ระบุ dependency array effect จะทำงานทุกครั้งที่ component render หากระบุ array ว่าง [] effect จะทำงานเพียงครั้งเดียวเมื่อ component mount
useContext เป็น Hook สำหรับเข้าถึง context value โดยตรง โดยไม่ต้องผ่าน props drilling รับ context object เป็นพารามิเตอร์และคืนค่า context value ปัจจุบัน ซึ่งช่วยให้องค์ประกอบที่อยู่ลึกใน tree สามารถเข้าถึงข้อมูล global ได้ง่าย
useRef เป็น Hook สำหรับสร้าง mutable reference object ที่ไม่ทำให้ component re-render เมื่อค่าเปลี่ยน เหมาะสำหรับการเก็บ DOM element reference หรือค่าที่ต้องการคงอยู่ตลอด lifecycle ของ component โดยไม่กระทบต่อการ render
Custom Hook — สร้าง Hook ของตัวเอง
Custom Hook คือ Hook ที่นักพัฒนาสร้างขึ้นเอง เพื่อ encapsulate logic ที่ใช้ซ้ำได้ ทำให้ code มีความ DRY (Don't Repeat Yourself) มากขึ้น
การตั้งชื่อ custom Hook ควรเริ่มต้นด้วย "use" เสมอ เช่น useFetch, useLocalStorage, useAuth เพื่อให้อ้างอิงได้ว่านี่คือ Hook
function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { return initialValue; } });
const setValue = (value) => { try { const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); window.localStorage.setItem(key, JSON.stringify(valueToStore)); } catch (error) { console.log(error); } };
return [storedValue, setValue]; }
// Usage function App() { const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
Custom Hook ช่วยแยก logic ออกจาก UI ทำให้ testing ทำได้ง่ายขึ้น และทำให้ component มีความ responsibility ที่ชัดเจน
Custom Hook คือฟังก์ชันที่เริ่มด้วยคำว่า use และเรียกใช้ Hook อื่นๆ ภายใน ทำให้สามารถ reuse logic ได้ระหว่าง component
ตัวอย่างการสร้าง Custom Hook ที่ใช้สำหรับ fetch ข้อมูล:
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}
ตอนนี้ component ใดๆ ก็เรียก useFetch ได้:
const { data, loading, error } = useFetch('https://api.example.com/users');
Custom Hook คือฟังก์ชัน JavaScript ที่ชื่อขึ้นต้นด้วย use ซึ่งสามารถเรียกใช้ Hook อื่นภายในได้ เป็นเครื่องมือทรงพลังสำหรับการจัดรูปแบบ logic ที่ใช้ซ้ำให้กลายเป็น reusable components ตัวอย่างเช่น หากมี logic สำหรับตรวจสอบการเชื่อมต่ออินเทอร์เน็ตที่ใช้ในหลาย component สามารถจัดรูปแบบเป็น useNetworkStatus Hook ได้
การสร้าง Custom Hook เริ่มจากการสร้างฟังก์ชันที่ชื่อขึ้นต้นด้วย use ภายในฟังก์ชันสามารถเรียกใช้ Hook อื่นได้ตามต้องการ เช่น useState, useEffect, useContext ตัวอย่างเช่น
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
};
return [storedValue, setValue];
}
Custom Hook นี้ encapsulate logic สำหรับจัดการ localStorage ทำให้ component ที่ต้องการใช้สามารถเรียกใช้ได้ง่ายเพียง const [value, setValue] = useLocalStorage('key', defaultValue)
Custom Hook คือการนำ Hook พื้นฐานมาประกอบกันเป็นฟังก์ชันที่มีหน้าที่เฉพาะเจาะจง โดยตั้งชื่อขึ้นต้นด้วย "use" เสมอ เช่น `useAuth` สำหรับจัดการยืนยันตัวตน `useLocalStorage` สำหรับอ่านเขียนข้อมูลใน Local Storage หรือ `useFetch` สำหรับดึงข้อมูลจาก API
การสร้าง Custom Hook ช่วยลด code duplication เมื่อหลายคอมโพเนนต์ต้องการ logic เดียวกัน ตัวอย่างเช่น `useWindowSize` ที่ติดตามขนาดหน้าจอและคืนค่า width/height ให้คอมโพเนนต์ใช้ได้เลย โดยคอมโพเนนต์ไม่ต้องเขียน logic การติดตามขนาดเอง
Custom Hook ยังช่วยให้ทดสอบ logic ได้ง่ายขึ้น เพราะแยกออกจาก UI ทำให้เขียน unit test สำหรับ logic ส่วนนั้นโดยตรงได้ โดยไม่ต้อง render คอมโพเนนต์จริง
Best Practices สำหรับการใช้ React Hook
การใช้ Hook อย่างมีประสิทธิภาพต้องการความเข้าใจใน best practices เพื่อหลีกเลี่ยงปัญหาที่พบบ่อย
กฎข้อแรกคือ Hook ควรเรียกที่ top level ของ component เท่านั้น ไม่ควรเรียกภายใน loops, conditions, หรือ nested functions
กฎข้อที่สองคือ Hook ควรเรียกใน component functions เท่านั้น ไม่ควรเรียกใน regular JavaScript functions
// ❌ BAD: Hook inside condition function Component() { if (condition) { const [state, setState] = useState(0); // Wrong! } }
// ✅ GOOD: Hook at top level function Component() { const [state, setState] = useState(0); if (condition) { // use state here } }
การติดตาม dependencies ใน useEffect เป็นสิ่งสำคัญมาก เพื่อหลีกเลี่ยง infinite loops และ stale closures
// ❌ BAD: Missing dependencies useEffect(() => { fetch(`/api/items/${id}`).then(res => res.json()).then(setItems); }, []); // Missing 'id' dependency
// ✅ GOOD: Complete dependencies useEffect(() => { let cancelled = false; fetch(`/api/items/${id}`).then(res => res.json()).then(data => { if (!cancelled) setItems(data); }); return () => { cancelled = true; }; }, [id]);
เรียก Hook ที่ top-level เสมอ — อย่าเรียกใน loop, condition หรือ nested function
ใช้ Rule of Hooks — Hook ต้องเรียกใน React function component หรือ Custom Hook เท่านั้น
ตั้ง dependencies array ให้ถูกต้องใน useEffect — อย่าลืม dependencies ที่ใช้
ใช้ ESLint plugin eslint-plugin-react-hooks เพื่อตรวจสอบกฎเหล่านี้
ตั้งชื่อ Custom Hook ให้เริ่มด้วย use เสมอ
แยก concerns — ใช้ Hook แยกกันสำหรับ state management, data fetching, และ event handling
ใช้ useMemo และ useCallback เมื่อจำเป็นเพื่อ optimize performance
ทำความเข้าใจ cleanup function ใน useEffect สำหรับ unmount logic
เพื่อใช้ Hook ได้อย่างมีประสิทธิภาพ ควรปฏิบัติตาม best practices ต่อไปนี้ เรียกใช้ Hook เฉพาะที่ top-level ของ component หรือ custom hook ไม่ควรเรียกใช้ Hook ภายในเงื่อนไข ลูป หรือ nested functions เพราะจะละเมิดกฎลำดับการเรียกใช้ Hook ที่คงที่
ใช้ dependency array อย่างถูกต้องกับ useEffect และ useCallback หากลืมใส่ dependency ที่จำเป็น effect อาจทำงานไม่ถูกต้องหากใส่ dependency เกินไป effect อาจทำงานบ่อยเกินจำเป็น
แยก logic ที่ใช้ซ้ำเป็น custom hook เมื่อพบ pattern ที่ใช้ซ้ำในหลาย component ควรจัดรูปแบบเป็น custom hook เพื่อเพิ่ม reusability และลด code duplication
ใช้ useMemo สำหรับ expensive computations และ useCallback สำหรับ callbacks ที่ส่งไปยัง child components เพื่อป้องกัน re-render ที่ไม่จำเป็น
ทดสอบ component ที่ใช้ Hook อย่างครอบคลุม โดยเฉพาะ edge cases ที่เกี่ยวกับ state changes และ effect execution
// ✅ Good: Custom hook for reusable logic
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
// ✅ Good: Proper dependency array
useEffect(() => {
fetchData(userId);
}, [userId]); // Only re-run when userId changes
กฎทองที่สำคัญที่สุดคือเรียก Hook เฉพาะที่ top-level ของคอมโพเนนต์หรือ Custom Hook เท่านั้น ห้ามเรียกในเงื่อนไข วนลูป หรือฟังก์ชันภายใน เพราะจะลำดับการเรียก Hook ที่ React ใช้ติดตาม state
ใช้ Dependency Array อย่างระมัดระวัง ใน `useEffect` และ `useCallback` ควรระบุ dependencies ครบถ้วน หากไม่แน่ใจให้ใช้ ESLint rule `exhaustive-deps` ช่วยตรวจสอบ
แยก logic ที่ไม่เกี่ยวกับ React ออกไปเป็นฟังก์ชันปกติ ไม่ต้องทำเป็น Hook เสมอไป Hook ควรใช้เฉพาะเมื่อต้องการ state หรือ interaction กับ lifecycle ของคอมโพเนนต์
ใช้ `useMemo` และ `useCallback` เฉพาะเมื่อจำเป็น จริง ๆ เพราะการ memoize ทุกอย่างอาจทำให้โค้ดซับซ้อนและ debug ยากขึ้น ควรใช้เมื่อมี performance issue จริง ๆ
ตัวอย่างการประยุกต์ใช้จริง
ในโปรเจกต์จริง Hook ถูกใช้กันอย่างหลากหลาย ตั้งแต่การจัดการ state จนถึงการ optimize performance
ตัวอย่างแรกคือการสร้าง custom hook สำหรับ authentication:
function useAuth() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true);
useEffect(() => { const token = localStorage.getItem('token'); if (token) { fetch('/api/me', { headers: { Authorization: `Bearer ${token}` } }) .then(res => res.json()) .then(setUser) .finally(() => setLoading(false)); } else { setLoading(false); } }, []);
const login = async (credentials) => { const res = await fetch('/api/login', { method: 'POST', body: JSON.stringify(credentials), }); const data = await res.json(); localStorage.setItem('token', data.token); setUser(data.user); };
const logout = () => { localStorage.removeItem('token'); setUser(null); };
return { user, loading, login, logout }; }
ตัวอย่างที่สองคือการจัดการ form state:
function useForm(initialValues) { const [values, setValues] = useState(initialValues); const [errors, setErrors] = useState({});
const handleChange = (field, value) => { setValues({ ...values, [field]: value }); setErrors({ ...errors, [field]: '' }); };
const validate = () => { const newErrors = {}; if (!values.email) newErrors.email = 'Email is required'; if (!values.password) newErrors.password = 'Password is required'; setErrors(newErrors); return Object.keys(newErrors).length === 0; };
return { values, errors, handleChange, validate }; }
Hook ทำให้การเขียน code มีความ modular มากขึ้น และช่วยให้ developer สามารถสร้าง reusable patterns ได้ง่ายขึ้น
ตัวอย่างที่ 1: Counter component ที่ใช้ useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
Count: {count}
);
}
ตัวอย่างที่ 2: Data fetching ที่ใช้ useEffect
import { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://api.example.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, []);
return (
- {user.name} )}
{users.map(user =>
);
}
ตัวอย่างที่ 3: Custom Hook สำหรับ window resize
import { useState, useEffect } from 'react';
function useWindowSize() {
const [size, setSize] = useState({ width: window.innerWidth, height: window.innerHeight });
useEffect(() => {
const handleResize = () => {
setSize({ width: window.innerWidth, height: window.innerHeight });
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
มาดูตัวอย่างการประยุกต์ใช้ Hook ในสถานการณ์จริง เริ่มจากตัวอย่างการจัดการ form state ด้วย useState
function ContactForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form submitted:', formData);
};
return (
);
}
ตัวอย่างที่สองคือการดึงข้อมูลจาก API ด้วย useEffect และจัดการ loading state
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchUser() {
try {
setLoading(true);
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
setUser(data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
}
fetchUser();
}, [userId]);
if (loading) return
if (error) return
return
}
ตัวอย่างที่สามคือการสร้าง custom hook สำหรับจัดการ window scroll position
function useScrollPosition() {
const [scrollPosition, setScrollPosition] = useState(0);
useEffect(() => {
const handleScroll = () => {
setScrollPosition(window.scrollY);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
return scrollPosition;
}
// Usage
function ScrollIndicator() {
const scrollY = useScrollPosition();
return
}
คำถามที่พบบ่อย
Hook ต่างจาก class component อย่างไร?
Hook ทำให้เราเขียน component แบบ function-based ได้เหมือน class component โดยไม่ต้องใช้ class syntax ซึ่งทำให้ code สั้นลงและอ่านง่ายขึ้น Hook สามารถใช้ state, lifecycle, และ context ได้เหมือน class แต่ด้วย syntax ที่ทันสมัยกว่าและมีความยืดหยุ่นมากกว่า
Hook สามารถใช้กับ library อื่นได้ไหม?
Hook เป็นฟีเจอร์ของ React เท่านั้น ไม่สามารถนำไปใช้กับ library อื่นได้โดยตรง แต่ library หลายตัวได้สร้าง React wrappers ที่มี Hook ให้ใช้ เช่น react-query, react-router-dom, และ react-hook-form
Custom Hook มีข้อจำกัดอะไร?
Custom Hook สามารถเรียก Hook อื่นภายในได้ แต่ต้องเรียกที่ top level เท่านั้น ไม่ควรเรียกภายใน conditions หรือ loops นอกจากนี้ custom Hook ไม่สามารถเก็บ state ของตัวเองได้โดยตรง ต้องใช้ useState หรือ useRef ภายใน hook เพื่อจัดการ state
แนะนำเพิ่มเติม
🎯 เปิดบัญชี XM Forex → สมัคร
📱 แอป iCafeFX → ดาวน์โหลด
📊 สัญญาณฟรี → รับสัญญาณ
📚 คู่มือเทรด → SiamCafeBook
🤝 สมัคร Partner XM → pipaffiliates.com/c?c=72816&l=th&p=6
ทดลองเทรดฟรี XM — โบรกที่ อ.บอม ใช้เทรดจริง (พาร์ทเนอร์ XM)
แนะนำจากเครือข่าย SiamCafe
คู่มือ Forex ที่เกี่ยวข้อง
แหล่งอ้างอิง
- SiamCafe.net - ชุมชนไอทีไทยตั้งแต่ปี 1997
- iCafeFX.com - ศูนย์วิเคราะห์ Forex และทองคำ