Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Konstantinacc/853a7217888245a609b606ce33a7e494 to your computer and use it in GitHub Desktop.
Save Konstantinacc/853a7217888245a609b606ce33a7e494 to your computer and use it in GitHub Desktop.
React example: calculate square of a number with useMemo
import React, { useState, useMemo } from "react";

const calculateSquare = (number) => {
  console.log("calculateSquare function called!");
  if (number === 0) return 0;
  return number * number;
};

const App = () => {
  const [number, setNumber] = useState(1);
  const [counter, setCounter] = useState(0);
  const squareResult = useMemo(() => calculateSquare(number), [number]);
  console.log("Rendering app");

  return (
    <>
      <div>Square of the following number: </div>
      <div style={{ marginTop: "0.5rem" }}>
        <input
          type="number"
          value={number}
          onChange={(event) => {
            setNumber(Number(event.target.value));
          }}
        />
      </div>
      <div style={{ marginTop: "0.5rem" }}>
        {" is "}
        {squareResult}
      </div>
      <div style={{ marginTop: "1rem" }}>{` Counter is: ${counter}`}</div>
      <div style={{ marginTop: "0.5rem" }}>
        <button onClick={() => setCounter(counter + 1)}>
          Increment counter
        </button>
      </div>
    </>
  );
};

export default App;

Code on codesandbox

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment