The useMemo

useMemo hook returns a memoized value. It only runs when one of its dependencies update.

syntax

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);


The useMemo and useCallback Hooks work on the same mechanism. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function. You can learn more about useCallback in the useCallback blog .

Example

Without useMemo

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [count, setCount] = useState(0);
  const [num, setNum] = useState(2);

  // expensiveFunction will run on every re-render even without any need.
  // If we increment the count this funtion will run
  // Although it should only run if num changes because
  // the num is being passed in this function.
  // useMemo FIXES THIS PROBLEM
  const result = expensiveFunction(num);

  const numChangeHandler = (e) => {
    setNum(Number(e.target.value));
  };

  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount((prevState) => prevState + 1)}>
        increment
      </button>
      <hr />
      <input
        type="number"
        value={num}
        placeholder="Enter Number"
        onChange={numChangeHandler}
      />
      <h1>{result}</h1>
    </div>
  );
}

const expensiveFunction = (num) => {
  console.log("running");
  for (let i = 0; i < 10000; i++) {
    num += 1;
  }
  return num;
};

With useMemo

import { useState, useMemo } from "react";
import "./styles.css";

export default function App() {
  const [count, setCount] = useState(0);
  const [num, setNum] = useState(2);

  // expensiveFunction will only run if num changes
  // will not run on every re-render
  const result = useMemo(() => expensiveFunction(num), [num]);

  const numChangeHandler = (e) => {
    setNum(Number(e.target.value));
  };

  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount((prevState) => prevState + 1)}>
        increment
      </button>
      <hr />
      <input
        type="number"
        value={num}
        placeholder="Enter Number"
        onChange={numChangeHandler}
      />
      <h1>{result}</h1>
    </div>
  );
}

const expensiveFunction = (num) => {
  console.log("running");
  for (let i = 0; i < 10000; i++) {
    num += 1;
  }
  return num;
};

UI output

use memo code ui output

Try to run this code to get the better understanding.

This is how useMemo works I hope you must have got the idea.

If you find it usefull please share with your network.

Happy Coding ๐Ÿ˜Š…