useMemo Hook React.js
Performance is an important aspect in programming, especially in large scale application. The useMemo hook is one tool that can be used to improve the performance of react app. In this tutorial I will try to demonstrate how and when to use useMemo hook.
Introduction to React useMemo
useMemo is one of the additional hooks that react provides. what useMemo does is it memoize the return value of a function. This means that I executes function that is passed to it and remembers its return value.
When the application is initially renders all the functions executes and on every re-render all the functions again executes. useMemo helps you to avoid the execution of functions on every render. useMemo only executes the function passed to it when certain condition is met.
When specified conditions are not met useMemo return the previous value of that function and avoids executing the function. This can help you optimize your react application by avoiding expensive calculation every time component re-renders.
Syntex
useMemo accepts two parameters the first one is the function to be executed and the second parameter is the array of dependence. Change of any value passed in the dependency array will the useMemo hook to executed the function again and recompute the memoized value. The useMemo hook will execute the function you passed as an argument after the initial render by default.
// Import useMemo from React:
import { useMemo } from 'react'
export default function App() {
// useMemo syntax example:
const memoizedValue = useMemo(() => {/* function to execute */}, [/* Dependencies */])
return (
<div ></div>
)
}
If we don't pass the dependency array the function will execute on every render.
const memoizedValue = useMemo(()=>{/* function to execute */})
If we pass empty dependency array the function will only execute on initial render.
const memoizedValue = useMemo(()=>{/* function to execute */},[])
When to use useMemo hook.
When there is an expensive calculation going on in the component the useMemo hook will come in handy. lets look into an example
import React,{useState} from 'react';
function MemoTutorial() {
const [count,setCount] = useState(0)
const [name,setName] = useState("")
const thousendNumber = expensiveFunction(count)
return (
<div>
<input type="number" value = {count} onChange={({target:{value}})=>setCount(parseInt(value))}/>
<input type="text" value={name} onChange={({target:{value}})=>setName(value)}/>
<div>{thousendNumber}</div>
</div>
)
}
function expensiveFunction (num) {
console.log('Expensive Function')
for (let i=0;i<1000000000;i++) {} // Expensive function
return num * 2
}
export default MemoTutorial
In the above example we have a function called expensiveFunction. Which by its name says that it is an expensive function. The expensiveFunction will take some time to return value. In the above example expensiveFunction will be executed on every render.
The only thing that is need in the expensive function is the value of count so if we follow best practices then the expensiveFunction should only run when the value of count changes. But right now the expensiveFunction will execute even if the values of name is changed.
To avoid this scenerio of running the function on every render useMemo comes into play .
import React,{useState,useMemo} from 'react';
function MemoTutorial() {
const [count,setCount] = useState(0)
const [name,setName] = useState("")
const thousendNumber = useMemo(()=>{
return expensiveFunction(count)
},[count])
return (
<div>
<input type="number" value = {count} onChange={({target:{value}})=>setCount(parseInt(value))}/>
<input type="text" value={name} onChange={({target:{value}})=>setName(value)}/>
<div>{thousendNumber}</div>
</div>
)
}
function expensiveFunction (num) {
console.log('Expensive Function')
for (let i=0;i<1000000000;i++) {} // Expensive function
return num * 2
}
export default MemoTutorial
In the above code we have wrapped the expensiveFunction in useMemo and we have set the dependence which will cause the re computation of the expensiveFunction. In our case dependency is count . Now if you run the code you will notice that every time the value of count is changed the expensiveFunction will get executed but if we change the value name the expensiveFunction will not be executed. By restricting the needless execution of expensive functions we optimize the performance of our react app.
Conclusion
The React useMemo hook can be useful when you look for ways to improve performance of your React app. It can help you optimize expensive computations by memoizing output of these computations and avoiding needless executions. I hope that this tutorial helped you understand what the useMemo hook is, how it works and also how to use it.
Subscribe to my newsletter
Read articles from Hamza Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Hamza Ali
Hamza Ali
Full stack Javascript Developer | Javascript, React, Typescript, Node/Express, MongoDB (MERN) ,SQL, PostgreSQL | Open source enthusiast