React Hooks เบื้องต้น - เตรียมพร้อมสำหรับ Dynamic UI
สร้าง static UI กันจนเป็นที่เรียบร้อยแล้ว ต่อไปเราจะเปลี่ยนให้เป็น dynamic ได้ แต่ก่อนอื่นต้องรู้จัก React Hooks พื้นฐานก่อน!
useState — เก็บข้อมูลที่เปลี่ยนแปลง
Section titled “useState — เก็บข้อมูลที่เปลี่ยนแปลง”useState ใช้เก็บ state ของ component — ข้อมูลที่เปลี่ยนได้เมื่อมี interaction
import { useState } from "react"
function Counter() { const [count, setCount] = useState(0) // state เริ่มต้น = 0
return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}> เพิ่ม </button> </div> )}ตัวอย่าง: Cart ที่มีปุ่มลบสินค้า
Section titled “ตัวอย่าง: Cart ที่มีปุ่มลบสินค้า”function Cart() { const [items, setItems] = useState([ { id: 1, name: "กระเป๋า", price: 1200 } ])
const removeItem = (id: number) => { setItems(items.filter(item => item.id !== id)) }
return ( <div> {items.map(item => ( <div key={item.id}> <span>{item.name}</span> <button onClick={() => removeItem(item.id)}> ลบ </button> </div> ))} </div> )}useEffect — ทำงานเมื่อ Component โหลด/อัปเดต
Section titled “useEffect — ทำงานเมื่อ Component โหลด/อัปเดต”useEffect ใช้ทำ side effects — งานที่ต้องทำนอกเหนือจาก render เช่น fetch data, subscribe, set timeout
import { useEffect, useState } from "react"
function ProductList() { const [products, setProducts] = useState([])
useEffect(() => { // ทำงานเมื่อ component โหลด (mount) fetch("/api/products") .then(res => res.json()) .then(data => setProducts(data)) }, []) // [] = dependency array
return <div>{/* แสดง products */}</div>}ตัวอย่าง: Search ที่ debounce
Section titled “ตัวอย่าง: Search ที่ debounce”function Search() { const [query, setQuery] = useState("") const [results, setResults] = useState([])
useEffect(() => { // debounce: รอให้พิมพ์เสร็จ 300ms ก่อนค้นหา const timer = setTimeout(() => { fetch(`/api/search?q=${query}`) .then(res => res.json()) .then(data => setResults(data)) }, 300)
// cleanup: ลบ timer เมื่อ query เปลี่ยน return () => clearTimeout(timer) }, [query])
return ( <input value={query} onChange={e => setQuery(e.target.value)} /> )}useRef — อ้างอิง Element ใน DOM
Section titled “useRef — อ้างอิง Element ใน DOM”useRef ใช้เก็บ reference ไปยัง element ใน DOM หรือค่าที่ไม่ต้องการให้ re-render
import { useRef } from "react"
function SearchInput() { const inputRef = useRef<HTMLInputElement>(null)
const handleFocus = () => { inputRef.current?.focus() // focus ไปที่ input }
return ( <> <input ref={inputRef} type="text" /> <button onClick={handleFocus}>ค้นหา</button> </> )}ตัวอย่าง: นับจำนวนครั้งที่ render
Section titled “ตัวอย่าง: นับจำนวนครั้งที่ render”function Counter() { const [count, setCount] = useState(0) const renderCount = useRef(0)
renderCount.current++ // นับทุกครั้งที่ render
return ( <div> <p>Render ครั้งที่: {renderCount.current}</p> <button onClick={() => setCount(count + 1)}>เพิ่ม</button> </div> )}useMemo — แคชค่าที่คำนวณแล้ว
Section titled “useMemo — แคชค่าที่คำนวณแล้ว”useMemo ใช้ cache ค่าที่คำนวณ เพื่อไม่ต้องคำนวณใหม่ทุกครั้งที่ render
import { useMemo, useState } from "react"
function ProductFilter() { const [search, setSearch] = useState("") const products = [{ name: "A" }, { name: "B" }, { name: "AB" }]
// คำนวณใหม่เฉพาะตอน search หรือ products เปลี่ยน const filtered = useMemo( () => products.filter(p => p.name.includes(search)), [search, products] )
return ( <div> {filtered.map(p => <div key={p.name}>{p.name}</div>)} </div> )}สรุป Part 3 — Mockup Pages
Section titled “สรุป Part 3 — Mockup Pages”ต่อไป: เราจะเปลี่ยน static UI ให้เป็น dynamic ด้วย state และ props — ใน Part 4: Props & State
Quiz: Mockup Pages & Hooks
ข้อ 1 / 50%