useMemo là một hook hiệu năng dùng để ghi nhớ giá trị được tính toán, nhằm tránh tính toán lại không cần thiết mỗi khi component re-render. Khác với useCallback được dùng để ghi nhớ lại hàm thay vì giá trị.

import { useMemo, useState } from "react";
 
function App() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState("");
 
  const expensiveCalculation = (num) => {
    console.log("Calculating...");
    for (let i = 0; i < 1e9; i++) {} // Giả lập tính toán nặng
    return num * 2;
  };
 
  const result = useMemo(() => expensiveCalculation(count), [count]);
 
  return (
    <div>
      <h2>Result: {result}</h2>
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
      <input value={text} onChange={(e) => setText(e.target.value)} />
    </div>
  );
}