0

The following UseMemo is not working. I am trying to memorize the square X^2 of number values. I type 3, to calculate data, then enter 4, and then 3 again. It recalculates each time. How can I fix this?

function App() {
  const [number, setNumber] = useState(1);

  const onChange = event => {
    setNumber(Number(event.target.value));
  };

  const squareResult = useMemo(() => calculateSquare(number), [number]);

  function calculateSquare(n) {
    console.log('numberSquare(n) called!');
    return n * n;
  }

  return (
    <div>
      <label htmlFor="test">Enter Number: </label>
      <input id="test" type="number" onChange={onChange}/>
      <h1>Data Square {squareResult}</h1>
    </div>
  );
}
mattsmith5
  • 540
  • 4
  • 29
  • 67

1 Answers1

1

The useMemo hook prevents the same (expensive) function from being called each time the component is re-rendered.

When the dependencies change, the function is re-run with the new arguments.

useMemo does not keep a historic set of results.

gunwin
  • 4,578
  • 5
  • 37
  • 59