
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;}
And we need the result of thisslowFunction
for rendering the webpage, for example, thecomplexResult
variable:
constcomplexResult=slowFunction(input);
<p>{complexResult}</p>
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 the
slowFunction
- the answer is the
complexResult
- the puzzle problem is the
dependency
.
How to useuseMemo
?
The prototype is given as follows:
constcachedValue=useMemo(calculateValue,dependencies);
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 codecachedValue
: the same result of calling calculateValue
Back to our example, previously we have:
constcomplexResult=slowFunction(input);
And withuseMemo
, this line could be changed into:
constcomplexResult=useMemo(()=>{returnslowFunction(input)},[input])
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;
What just happened after clicking the change color button?
setColor
triggered re-render- Recalculate
doubledNumber
takes lots of time - Lead to slow render of
doubledNumber
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;
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:
- Overusing
useMemo
can hurt performance and introduce unnecessary overhead. - Memoization is most effective forexpensive computations that produce the same output for the same inputs.
- Overusing
useMemo
can make your code harder to read and maintain.
Reference
- useMemo. React. (n.d.). Retrieved April 25, 2023, fromhttps://react.dev/reference/react/useMemo
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse