The what and how of useMemo hook

Riya AgarwalRiya Agarwal
2 min read

For a long time, useMemo had been a mystery to me. Now that I understood it, I thought of documenting everything the way I understand it so that other fellow developers may also benefit.

What is useMemo used for?

useMemo is used to avoid running a resource-intensive (expensive) task unnecessarily.

What does expensive or resource-intensive mean?

A task that uses a lot of time, space, or resources is called expensive or resource-intensive.

So, how does useMemo help?

Well, it just “memo”izes the output of the previous execution and, if asked for, presents it without rerunning the expensive task if the requirements do not change.

Hence, the name useMemo.

Syntax

import { useMemo } from “react”

const cachedValue = useMemo(() => expensiveFuncCall(param), [param]);

The following are the 2 components of using the useMemo hook:-

  1. Import useMemo just as you would import useState

  2. Declare it at the top level of the component just like any other hook

It takes 2 arguments:-

  1. A function to execute the resource-intensive task.

  2. An array of dependencies that have been used inside the function.

A catch to catch

The useMemo hook only caches the last output of the function. If a call is made to the function in useMemo with a new argument, the function has to run again to calculate the new value, which will then be stored by useMemo.

Happy memoing! :)
0
Subscribe to my newsletter

Read articles from Riya Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Riya Agarwal
Riya Agarwal