UseMemo

Mukulved
2 min readMar 31, 2024

--

React useMemo() hook is a function that caches the value produced from an expensive function used inside a React component. It accepts the expensive function and works by storing the value produced from the function when that is passed the same arguments repeatedly. When different arguments are passed, it returns the new value and updates the cache.

Caching an expensive function’s value with useMemo is useful in optimizing the performance of a React component - as doing so minimizes repeating heavy computations.

Resource Intensive Functions in React: Why Use React useMemo ?

An expensive function is typically a resource intensive function that performs heavy and repetitive computations. In React, data processing, transformation and manipulation utilities like sorting functions, filters and mappers are commonly used costly functions. Such data heavy functions consume a lot of application resources (memory and time, which cost the application with billing). They slow down a React application and contributes to poor performance.

useMemo's caching helps bypass the expensive function's repetitive heavy processes when it is invoked with the same parameters - thereby improving performance of the React component.

Optimizing Expensive Utility Functions with React useMemo Hook

In the sections that follow, we demonstrate the use of React useMemo hook in a demo blog app that we explored in Part I. Part I demonstrates the use of React.memo for memoizing a component, i.e. the <Post /> component.

In this post, we’ll implement caching of a sorting function with useMemo() and examine how it prevents recalculation tasks from the browser's console.

But before that, let’s get a refresher of what’s going on in the demo app.

--

--