CONTACT US
TABLE OF CONTENTS

How To Use Memoization in JavaScript and React?

Jakub Dakowicz
By Jakub DakowiczPublication: Update:
A close-up of a model human brain on a stand, showing detailed grooves and folds, evokes concepts like memoisation in React, set against a blurred grey background.

First things first, Memoization in React development is caching.

But “caching” is a general term, and memoization is a specific form of caching.
It is an optimization technique, which speeds up apps by caching the results of function calls and returning the stored result when the same arguments are supplied again. And it’s loved by many React companies.

When you should apply Memoization?

  • It can perform heavy, time-consuming computings, therefore storing the result might help you save some processing time in our application.
  • Function consistently receives the same arguments, which waste time by re-computing the same.

Requirements

The function which we want to memoize should follow the principles of purity. It means that the result should depend only on arguments, and it should always return the same data for the same arguments passed.
In this way, we can do a memoization layer that’s automatic and argument-dependent. This is pivotal for the technique to work consistently.

Without Memoization

function fib(n) {
  if (n === 0) {
    return 0
  }
  if (n === 1) {
    return 1
  }
  return fib(n-1) + fib(n-2)
}

With Memoization

function fibMemo(n) {
 if (!fibMemo.cachedResults) {
  fibMemo.cachedResults = {}
 }
 if (!fibMemo.cachedResults[n]) {
  if (n === 0) {
   fibMemo.cachedResults[n] = 0
  } else if (n === 1) {
   fibMemo.cachedResults[n] = 1
  } else {
   fibMemo.cachedResults[n] =
   fibMemo(n-1) + fibMemo(n-2)
  }
 }
 return fibMemo.cachedResults[n]
}

Use higher-order function

function memoizer(fn) {
  const cachedResults = {}
  return function (...args) {
    const key = JSON.stringify(args)
    if (!cachedResults[key]) {
      cachedResults[n] = fn(args)
    }
    return cachedResults[key]
  }
}

Memoization in React

React.memo

It is similar in functionality to PureComponent which helps us have finer control over the rendering of our component.
The default behavior of a component declared using React.memo is that it renders only if the props have changed. It does a shallow comparison of the props to check that but there is an option to override that as well.

React.memo(component, compareFn)
const MyComponent = React.memo(props => <>...</>)

The second parameter compareFn is just like shouldComponentUpdate lifecycle in the class component but with one difference.

In shouldComponentUpdate we need to return true to rerender the component. In React.memo, compareFn returns if the props passed are the same; so to rerender we need to return false.

useMemo Hook

useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

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

Conclusion

It’s best to implement memoization on functions that are pure and involve heavy, repetitive calculations.

Jakub Dakowicz

Jakub Dakowicz is CTO at Pagepro, a software house specializing in Next.js and Sanity migrations. He joined over ten years ago as a junior developer and now owns the technology decisions, delivery processes and code quality behind every project the team ships. Jakub is the person behind the standards Pagepro's migrations run on - Nexity, the in-house Next.js and Sanity framework, and the project starter that makes each new site cheaper and less buggy than the last. Recently he led few WordPress-to-Next.js migrations and has been building quick prototypes - usually a working preview in the client's hands within a day - so decisions get made on something real instead of a slide. He spends a lot of his time on AI-assisted development - agents, coding tools and treating the repository as a living knowledge base for both the team and the models. He speaks about it at local tech meetups and writes about migrations, headless architecture and how AI changes the way agencies build. Politechnika Białostocka alumnus, based in Białystok.

Article link copied

Close button