Apr 8th, 2022 - written by Kimserey with .
useMemo
hook in React can be used to memoize values. Memoization is used as an optimization by caching previous result of computation and directly returning the result when teh same inputs are requested. In today’s post, we’ll look at how we can use useMemo
.
useMemo
HookUnderstanding memo with an example is straight forward:
1
2
3
4
5
6
7
8
9
10
const MyComponent: FC<{ msg: string }> = ({ msg }) => {
const appendTest = (message: string) => {
console.log("called");
return message + " test";
};
const value = appendTest(msg);
return <>{value}</>;
};
We have a component accepting a prop msg
, which internally has a function declared which gets called within the body of our function component. The fact that it is defined and called within the body makes it such that at every render, the function appendTest
will be called, regardless of whether msg
has changed or not.
We can see that by checking the console log where we print "called"
.
To optimize those calls, we can wrap the call to appendTest
into useMemo
:
1
const value = useMemo(() => appendTest(msg), [msg]);
The second argument is an array which identify the dependencies on which the memoized function will be reexecuted. It’s important to have that array right as it can lead to bugs where the result is still based on passed values. It is recommended to use the exhaustive-deps
rule to make sure we don’t forget any dependencies.
The dependency would include whatever argument is passed to appendTest
but also any dependency referenced within appendTest
.
Here is a full example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const MyComponent: FC<{ msg: string }> = ({ msg }) => {
const appendTest = (message: string) => {
console.log("called");
return message + " test";
};
const value = useMemo(() => appendTest(msg), [msg]);
return <>{value}</>;
};
const App: FC = () => {
const [state, setState] = useState("");
const [date, setDate] = useState(new Date().toISOString());
useEffect(() => {
const interval = setInterval(() => {
setDate(new Date().toISOString());
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<>
<button onClick={() => setState(new Date().toISOString())}>Click</button>
<MyComponent msg={state}></MyComponent>
<p>{date}</p>
</>
);
};
By running this example we can see that the memo is caching the result of appendTest
as even thought MyComponent
is being rendered at every change of our date
state, the call to appendTest
only happens when we click the button.
And that concludes today’s post!
Today we looked at useMemo
hook. We started by explaining what the purpose of memoization was, and then moved on to using the hook in our example seeing how it changes the behaviour of the code. Hope you liked this post and I’ll see you on the next one!