Pagepro Blog

JavaScript

How To Use Memoization in JS and React?

Posted on .

How To Use Memoization in JS and React?

Introduction

First things first, Memoization 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.

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 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 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.

Rafał Golubowicz

Rafał Golubowicz

There are no comments.

View Comments (0) ...
Navigation