DEV Community

Ayako yk
Ayako yk

Posted on

Exploring useMemo in React: Optimization and Real-World Applications

I recently joined a new team and kicked off a project with TypeScript and NextJS. As I delved into the project, which happens to be quite extensive, I observed that the useMemo function is being used quite often. While I have a basic understanding of it, I believe it's high time to grasp it more profoundly.

I plan to discuss the details of useMemo and explore the reasons behind its frequent use in our project.

useMemo(calculateValue, dependencies)

Definition
useMemo is a React Hook designed for caching data to optimize performance. The term "memo" is derived from memoization. (not memo nor memorization!) It should be placed at the top level of the component.

calculateValue is a function intended for computation within the component.

dependencies is an array containing values.

When the component renders initially, useMemo is invoked. Subsequently, whenever the value(s) in the dependencies change, calculateValue runs. If the values in the dependencies remain unchanged, the cached data is utilized, preventing unnecessary renders.

In Strict Mode, React calls the calculation function twice to maintain component purity, ensuring React components yield the same output for the same input. This behavior is exclusive to development mode and does not affect the logic.

The example from the React documentation provides detailed explanations along with code snippets.

React

Briefly, the utilization of useMemo in the example is aimed at preventing unnecessary re-renders by employing caching, resulting in optimizing rendering performance.

======================================================

The project I am currently involved in frequently utilizes useMemo for displaying options in the select tag. I can't share our project here, so let's consider an e-commerce website for a clothing shop. When filtering categories, the application employs cascading filters to narrow down results while preserving broader selections.

Clothes --> Accessories --> Hats --> Knit hats

This cascading filtering mechanism using useMemo effectively avoids unnecessary re-rendering.

useMemo is a great tool for optimization; however, as the documentation mentions, interactions are fast enough even without using memoization. Therefore, I would need to consider the reasons why we should or should not use certain features.

Top comments (2)

Collapse
 
mattlewandowski93 profile image
Matt Lewandowski

I find that useMemo often gets overused if you are using useEffect to fetch data. If you have a value being used by a useEffect, and it is not memoized, you are potentially going to create an infinite loop.

Collapse
 
ayako_yk profile image
Ayako yk

Thank you for your insight, Matt. I didn't notice that point. So, I should be mindful of not creating an infinite loop by not memoizing values used by useEffect.