...

/

Testing and Examples of the useMemo Hook

Testing and Examples of the useMemo Hook

Learn about the practical application of the useMemo hook in React to enhance performance and optimize user experiences

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.

Press + to interact
...