How to use useMemo in React

Kola Grey
1 min readDec 10, 2022
Photo by Lautaro Andreani on Unsplash

useMemo is a React hook that allows you to optimize the performance of your components by memoizing expensive function calls. It works by storing the results of the function in memory and returning the cached result when the function is called with the same arguments. This can be useful when you have a component that performs a lot of computations and you want to avoid recomputing them every time the component renders.

To use useMemo, you need to pass two arguments to the hook: the function to be memoized and an array of dependencies. The hook will only re-compute the result of the function if one of the dependencies has changed.

Here’s an example of how you might use useMemo in a React component:

import React, { useMemo } from 'react';

function MyComponent(props) {
// Use the useMemo hook to memoize the expensive function
const result = useMemo(() => expensiveFunction(props.a, props.b), [props.a, props.b]);

return <div>{result}</div>;
}

In this example, the expensiveFunction will only be called if props.a or props.b changes. If these values remain the same, the result will be retrieved from the memoized cache. This can help improve the performance of your component by avoiding unnecessary calculations.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kola Grey
Kola Grey

Written by Kola Grey

Currently working within the following ecosystem: Web. Mobile. Social Media. Exploring more ways to deliver more value. Discovery in motion...

No responses yet

Write a response