ทั้งคู่จัดเก็บสิ่งของข้อมูลบนการ render เพื่อไม่ให้มันถูกคำนวณ/สร้างใหม่ทุกครั้ง:
useMemoจัดเก็บ
ทั้งคู่จัดเก็บสิ่งของข้อมูลบนการ render เพื่อไม่ให้มันถูกคำนวณ/สร้างใหม่ทุกครั้ง:
useMemo จัดเก็บ useCallback จัดเก็บ identity ของฟังก์ชัน (มันคือ useMemo(() => fn, deps)).มันมีอยู่เพื่อหลีกเลี่ยง (a) การทำงานที่ใช้ต้นทุนสูงซ้ำแล้วซ้ำอีก และ (b) การทำลาย referential equality ที่ memoized children ต้องพึ่งพา
function Table({ rows, onSelect }) {
// (a) expensive computation — recompute only when `rows` changes
const sorted = useMemo(() => rows.slice().sort(byName), [rows]);
// (b) stable function identity — so a React.memo child doesn't re-render,
// and effects depending on it don't re-fire
const handleSelect = useCallback(id => onSelect(id), [onSelect]);
return <Grid rows={sorted} onSelect={handleSelect} />;
}
โดยไม่มี useCallback handleSelect คือฟังก์ชันใหม่อย่างสมบูรณ์ในแต่ละการ render React.memo(Grid) จะเห็น prop "ใหม่" และยังคงทำการ render ใหม่ จึงทำให้การ memoization ล้มเหลว สิ่งเดียวกันนี้เกิดขึ้นกับอ็อบเจ็กต์ที่ส่งผ่านไปยัง memoized child หรือใช้ในอาร์เรย์ dependency ของ useEffect
const x = useMemo(() => a + b, [a, b]); // ❌ pointless — adding is cheaper than memoizing
useMemo/useCallback ในทุกที่เพิ่มเสียงรบกวนและอาจช้าลงได้ (Compiler ของ React 19 สามารถ auto-memoize ได้ ลดความจำเป็น)