Search code examples
reactjsreact-usememo

React, Have UseMemo work correctly with textbox


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>
  );
}

Solution

  • 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.