How to Effectively Memoize Methods in React Class Components with Lodash

Mohsen Taleb
3 min readFeb 29, 2020

--

A while ago when I was refactoring a React code base which was written in Class component style, I was faced with a method which did a very expensive calculation and it was called in every re-render, hence, making that component very slow.

The solution, obviously, was to make that method somehow “cache” the results. But how?

Referring to React’s documentations about memoization, they’ve introduced 3 different approaches for this matter:

  1. Using getDerivedStateFromProps, which is not recommended since it adds extra complexity of tracking changes for both state and props.

2. Using a PureComponent instead of a regular class component which under the hood implements a shouldComponentUpdateand does a shallow comparison of both state and props before re-rendering.

3. The recommended one, using a third party memoization library

What I’m about to explain here, is taking the third approach using lodash memoize function and elaborate on some advanced usages which are not available in their documentations.

Use Case

Let’s assume we’re building a component for displaying a large list of real-estate items and then we want to sort them locally by an…

--

--