When to use React useMemo hook with Examples

When to use React useMemo hook with Examples

In this tutorial, we are going to learn about when to use react useMemo() hook with the help of examples.

useMemo hook

The useMemo hook is used to memoize the function return value, so that function only recomputes the value when one of its dependencies are changed.

First, let’s see an example without using useMemo hook.

import React, { useState} from "react";

function Welcome() {
  const [msg, setMsg] = useState("hello");
  const reverseMsg = () => {    return msg.split("").reverse().join("");  }  return (
    <div>
      <h1>{msg}</h1>
      <h1>{reverseMsg()}</h1>      <h1>{reverseMsg()}</h1>      <button onClick={() => setMsg("Hello")}>Change Msg</button>
    </div>
  );
}

export default Welcome;

In the above, we have used reverseMsg() function in two places but both times we are running the function to get the same result.

Now, let’s wrap the function with useMemo() hook.

import React, { useState} from "react";

function Welcome() {
  const [msg, setMsg] = useState("hello");
  const reverseMsg = useMemo(() => {    return msg.split("").reverse().join("");  },[msg]); //msg is dependency
  return (
    <div>
      <h1>{msg}</h1>
      <h1>{reverseMsg}</h1>      <h1>{reverseMsg}</h1>      <button onClick={() => setMsg("Hello")}>Change Msg</button>
    </div>
  );
}

export default Welcome;

In the above code, we wrapped the function with useMemo() hook and it returns a memoized value or cached value, which is stored inside the reverseMsg variable.

Now we can use reverseMsg in multiple places but the function will only run once and next time it will return the value immediately from the cache.

The useMemo hook will only re-run the function again when one of its dependencies are changed.

It means if we click on a Change Msg button it will update the msg property. so useMemo hook dependency is changed and re-run the function again to get the new cached value.