Let's learn about useMemo in React!
March 09, 2024
Background
I saw the useMemo
hook in one project. It's not famlilar for me, beacuse I just had understand the surface of React. Throught this time, I will have chance to understand useMemo
. Maybe, It's gonna be making new post about react hook actually.
useMemo
Actually, I had been trapped becuase React DoC says 'It will be okay for developoing with React, if you just know three hooks, "useState", "useEffect", "useContenxt"'. It's some overstated LOL.
Anyway, useMemo
formats follows under state.
const cachedValue = useMemo(calculateValue, dependencies);
useMemo
is used to remember the result value required much computing source. So you can use this hook for optimizing to render your React components.
Params
-
calculateValue
calculateValue
is a function which have no arguments, return a value in any type, and should be pure. Re-rendering your components, React just return pre-value already made without calcluating new value ifdependencies
is not changed. -
dependencies
dependencies
can be props, states, functions, and all variables used in a components. React check if this dependencies changed and calculate new value throughcalculateValue
and return the value.
Use Case
import { useMemo } from 'react';
const getList = (users, date) => {
return users.filter(
user => user.createDate > date && user.createDate < date + 1 HOUR
);
}
export default function UserList({users, date}){
const now = new Date();
const usersFiltered = useMemo(()=> getList(), [users, date]);
return (
<ul>
{usersFiltered.map((value)=>{
return (
<li>
{user.name} | {user.telephone} | {user.createDate}
</li>
)
})}
</ul>
)
}
In avobe case, React doesn't calculate usersFiltered
again until the dependecies, users
, date
is changed. So you can save the resource for re-render UserList
component.