We can use the React useMemo
hook to cache computed values.
In this article, we’ll look at how to use the React useMemo
hook to cache computed values.
Memoize Values with the React useMemo Hook
We can also use the useMemo
hook to create a memoized values, which means that it’s cached as long as it or its dependencies don’t change.
useMemo
runs during rendering. Therefore, we shouldn’t run anything that we wouldn’t do during rendering.
It’s used as a performance optimization, but it’s not a guarantee of the integrity of the value because it might change later.
For instance, we can use it as follows:
import React from "react";
export default function App() {
const [firstName, setFirstName] = React.useState("");
const [lastName, setLastName] = React.useState("");
const name = React.useMemo(() => `${firstName} ${lastName}`, [
firstName,
lastName
]);
return (
<div>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
<input value={lastName} onChange={e => setLastName(e.target.value)} />
<p>{name}</p>
</div>
);
}
In the code above, we used useMemo
to watch firstName
and lastName
‘s values and then derive a new value name
from combining the 2.
Then when we enter text into the input, we’ll see that it updates the value of name
. However, it’ll cache the existing value if firstName
or lastName
don’t change.
Conclusion
We can also use the useMemo
hook to create a memoized values, which means that it’s cached as long as it or its dependencies don’t change.