Search⌘ K

Testing and Examples of the useMemo Hook

Explore how to test and implement the useMemo hook in React to enhance application performance. Learn how caching values with useMemo can minimize recalculations during user input, improving responsiveness and user experience in search functions and similar scenarios.

Testing the useMemo hook

Let's implement an example with the useMemo hook to gain some performance:

const Title = ({ text, flag }) => {
// Memoizing the result of matchTextInArray to avoid unnecessary recalculations
const found = useMemo(() => {
console.log('created') ➀
return matchTextInArray(text)
}, [text])
console.log('updated', found) ➁
}
React component using useMemo to memoize matchTextInArray(text) result with creation and update logs

The preceding code replaces useState and useEffect with useMemo. Let's take a look at the timeline to see what difference it makes:

|----TFTF--------TF------> flag
----------a---------b----> text
R----RRRR-R---------R----> updated ➁
c---------c---------c----> created ➀

A new value is created in the "created" series when the text changes, independent of the flag flips. Even better this time, there's no delay between assigning the found value and receiving the text change because it's a direct assignment under the same update now.

It's important to note that with or without useMemo, there's no big code structure change introduced to address the performance issue. In fact, to switch back to the ...