ใช้สำหรับจัดการ state ใน Component
ใช้เพื่อจัดการ state ภายใน functional component
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
ใช้แทน useState
เมื่อ state มีความซับซ้อนมากขึ้น
import { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<span>{state.count}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}
ช่วยเพิ่มประสิทธิภาพของ Component
ใช้เมมโมไรซ์ค่าที่คำนวณ เพื่อป้องกันการคำนวณซ้ำ ๆ
import { useState, useMemo } from 'react';
function ExpensiveComponent({ num }) {
const squared = useMemo(() => {
console.log('Calculating square...');
return num * num;
}, [num]);
return <p>Square: {squared}</p>;
}
ใช้เมมโมไรซ์ฟังก์ชัน เพื่อป้องกันการสร้างใหม่ทุกครั้งที่ re-render
import { useState, useCallback } from 'react';
function Button({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('Clicked!');
}, []);
return (
<>
<Button onClick={handleClick} />
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
</>
);
}
ใช้สำหรับทำงานที่มีผลกระทบต่อ Component เช่น API calls หรือ DOM updates
ใช้สำหรับทำ side effects เช่น เรียก API หรือ subscribe event
import { useState, useEffect } from 'react';
function FetchData() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []); // Empty dependency array = run once on mount
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
เหมือน useEffect
แต่จะรันก่อน React วาด UI ลง DOM
import { useLayoutEffect, useRef } from 'react';
function LayoutEffectExample() {
const ref = useRef(null);
useLayoutEffect(() => {
console.log('Before painting:', ref.current);
}, []);
return <div ref={ref}>Hello</div>;
}
ใช้แชร์ข้อมูลระหว่าง Components หรือจัดการค่าแบบไม่ต้อง re-render
ใช้ร่วมกับ Context API เพื่อแชร์ข้อมูลระหว่าง Components
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
ใช้เก็บค่าแบบไม่ทำให้ Component re-render (เช่น DOM elements หรือ previous state)
import { useRef } from 'react';
function InputFocus() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} type="text" />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</>
);
}
ช่วยให้ UI ตอบสนองดีขึ้น
ช่วยให้ UI ไม่กระตุกเมื่อเปลี่ยน state
import { useState, useTransition } from 'react';
function TransitionExample() {
const [count, setCount] = useState(0);
const [isPending, startTransition] = useTransition();
return (
<>
<button onClick={() => startTransition(() => setCount(count + 1))}>
Increment
</button>
{isPending ? <p>Loading...</p> : <p>Count: {count}</p>}
</>
);
}
ใช้ใน Server Components เพื่อแทรก HTML ลงใน response
import { useServerInsertedHTML } from 'react-dom';
export default function ServerComponent() {
useServerInsertedHTML(() => <style>{'body { background: black; }'}</style>);
return <p>Server-side styled component</p>;
}
Hook | ใช้ทำอะไร? |
---|---|
useState |
จัดการ state ของ Component |
useReducer |
จัดการ state ที่ซับซ้อน |
useEffect |
จัดการ side effects เช่น API calls |
useLayoutEffect |
ทำงานก่อน UI ถูกวาดลง DOM |
useMemo |
เมมโมไรซ์ค่าที่คำนวณ |
useCallback |
เมมโมไรซ์ฟังก์ชัน |
useRef |
เก็บค่าที่ไม่ทำให้ Component re-render |
useContext |
ใช้ค่าจาก Context API |
useTransition |
ทำให้ UI เปลี่ยนแปลงแบบ smooth |
💖 หวังว่าเธอจะเข้าใจ Hooks ได้ง่ายขึ้นนะ! 😘