I was trying to help a backend developer friend of mine with an example of when and how to make use of the useMemo() hook in React.
And ended up with a new post 😄.
So, what is useMemo? The useMemo()
hook serves as a cache mechanism and it is useful in telling React to only recalculate a value only when one dependency changes.
Take for example this code:
const expensiveCalculation = (value)=> {
alert('⏳ Running expensive computation')
return value * 2
}
const WithoutUsingMemo = () => {
const [green, setGreen] = useState(0)
const [red, setRed] = useState(0)
const result = expensiveCalculation(red)
console.log(result)
return (<div>
<h3>Without memo the expensive computation will run on 🍏 and 🍎</h3>
<p>🍏={green} and 🍎={red}</p>
<button onClick = {() => setGreen(val => val+1)}>
Add 🍏 apple
</button>
<button onClick = {() => setRed(val => val+1)}>
Add 🍎 apple
</button>
</div>)
}
It will produce the below React component:
Each time the user will press one of the buttons the expensiveCalculation()
will be called.
And we don't want what because only the red
variable matters for the expensiveCalculation()
function. In JS we only have one main thread, and we're keeping it super busy by running this code repeatedly at each render of the component.
What we can do to wrap all the expensive calculations into a useMemo()
, cache the result, and recalculate it only when the dependencies are changing.
In our case, the only dependency is the red
state variable:
const UsingMemo = () => {
const [green, setGreen] = useState(0)
const [red, setRed] = useState(0)
/* with useMemo() the expensiveCalculation()
will run only when red changes, instead of each render */
const result = useMemo( ()=> {
return expensiveCalculation(red)
}, [red])
console.log(result)
// ... same as above
}
As usual, you can check the full code for this example on GitHub and see it live on GitHub Pages.
As a final note, useMemo()
is similar to useEffect()
hook as it accepts a function and a list of dependencies but it returns the memoized value returned by the passed function and also recalculates the value only when one of its dependencies changes.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.