Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for React `UseMemo`
Kexuan (Michael) Huang
Kexuan (Michael) Huang

Posted on

React `UseMemo`

What isuseMemo?

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.

Typically,useMemo reduces the amount of work that needs to be done in a given render.useMemo can memoize the function and its result, meaning that if the inputs of the function do not change, React will return the memoized value instead of recomputing it, which will potentially speed up your render process.

A Simple Explanation

Let's say we have a really slow function which takes up huge amount of time to computer in the render process:

// a really slow function...constslowFunction=(num)=>{for(leti=0;i<1000000000;i++){}returnnum*2;}
Enter fullscreen modeExit fullscreen mode

And we need the result of thisslowFunction for rendering the webpage, for example, thecomplexResult variable:

constcomplexResult=slowFunction(input);
Enter fullscreen modeExit fullscreen mode
<p>{complexResult}</p>
Enter fullscreen modeExit fullscreen mode

In this case, callingslowFunction in every render will significantly slow down your application. This is whereuseMemo comes in handy.

We can wrap theslowFunction insideuseMemo and provide an array of dependencies. The array of dependencies is used to determine whether or not the memoized value should be recalculated. If any of the dependencies change,useMemo will recalculate the memoized value, or it will just use the previous "memoized" value.

A simple metaphor would be:

  • if I'm solving the puzzle for the first time, I have to take time to go through every steps until I solve it and give the answer.
  • If you ask me to solve the same puzzle the second time, I don't have to go through all the steps once again. Instead, I just give you the answer directly because it's already in my brain.
  • If you ask me to solve another different puzzle, I still have to take time to go through every steps.

Here:

  • the process of solving the puzzle is theslowFunction
  • the answer is thecomplexResult
  • the puzzle problem is thedependency.

How to useuseMemo?

The prototype is given as follows:

constcachedValue=useMemo(calculateValue,dependencies);
Enter fullscreen modeExit fullscreen mode

where

  • calculateValue: The function calculating the value that you want to cache. (typically slow functions)
  • dependencies: The list of all reactive values referenced inside of the calculateValue code
  • cachedValue: the same result of calling calculateValue

Back to our example, previously we have:

constcomplexResult=slowFunction(input);
Enter fullscreen modeExit fullscreen mode

And withuseMemo, this line could be changed into:

constcomplexResult=useMemo(()=>{returnslowFunction(input)},[input])
Enter fullscreen modeExit fullscreen mode

In the example above,complexResult will only be recalculated if theinput dependency changes. Ifinput stays the same, React will return the previously memoized value, which saves us from callingslowFunction again and again.

A Complete Example

In case you still find this concept abstract or just need some contexts to think over. A slightly more complex example is provided below.

WithoutuseMemo

import{useState}from"react";constslowFunction=(num)=>{console.log("running slow double calculation...");for(leti=0;i<1000000000;i++){}returnnum*2;};constDemo=()=>{const[number,setNumber]=useState(0);const[color,setColor]=useState("black");constdoubledNumber=slowFunction(number);return(<div><inputtype="number"value={number}onChange={(e)=>setNumber(e.target.value)}/><buttononClick={()=>setColor(color==="black"?"green":"black")}>ChangeColor!</button><pstyle={{color:color}}>{doubledNumber}</p></div>);};exportdefaultDemo;
Enter fullscreen modeExit fullscreen mode

What just happened after clicking the change color button?

  1. setColor triggered re-render
  2. RecalculatedoubledNumber takes lots of time
  3. Lead to slow render ofdoubledNumber

WithuseMemo

import{useState,useMemo}from"react";constslowFunction=(num)=>{console.log("running slow double calculation...");for(leti=0;i<1000000000;i++){}returnnum*2;};constDemo=()=>{const[number,setNumber]=useState(0);const[color,setColor]=useState("black");constdoubledNumber=useMemo(()=>{returnslowFunction(number);},[number]);return(<div><inputtype="number"value={number}onChange={(e)=>setNumber(e.target.value)}/><buttononClick={()=>setColor(color==="black"?"green":"black")}>ChangeColor!</button><pstyle={{color:color}}>{doubledNumber}</p></div>);};exportdefaultDemo;
Enter fullscreen modeExit fullscreen mode

Thanks touseMemo, we no longer have to wait for a long time for setting color after changing the number.

Reminder: Don’t useuseMemo everywhere!

The reasons are:

  • OverusinguseMemo can hurt performance and introduce unnecessary overhead.
  • Memoization is most effective forexpensive computations that produce the same output for the same inputs.
  • OverusinguseMemo can make your code harder to read and maintain.

Reference

  1. useMemo. React. (n.d.). Retrieved April 25, 2023, fromhttps://react.dev/reference/react/useMemo

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp