How to use useMemo React hook

Find out what the useMemo React hook is for and how to use it!

Look at mineIntroduction to React hooksFirst of all, if you are a novice to them.

One of the React hooks I sometimes use isuseMemo.

import React, { useMemo } from 'react'

This hook is used to create a memory value.

This hook is very similar touseCallback,the difference lies inuseCallbackReturn a memoized callback, anduseMemoReturn a memory value, that is, the result of the function call. The use cases are also different.useCallbackUsed for callbacks passed to child components.

Sometimes, you have to calculate values through complex calculations or through access to databases for expensive queries or through the network.

With this hook, this operation is performed only once, then the value will be stored in the stored value, and next time you want to reference it, it will get it faster.

The method of use is as follows:

const memoizedValue = useMemo(() => expensiveOperation())

Make sure to add an empty array as the second parameteruseMemo(), Otherwise no recording will be made.

If you need to pass parameters, you also need to pass parameters in the array:

const memoizedValue = useMemo(() => expensiveOperation(param1, param2), [param1, param2])

If one of the parameters changes when you try to access the value, of course the value will be calculated without a memo.

Download mine for freeResponse Handbook


More response tutorials: