Skip to main content

Command Palette

Search for a command to run...

useMemo and useCallback hook

Published
•2 min read•View as Markdown
useMemo and useCallback hook

One thing to always remember is that use the useMemo hook only when you are doing something that is computationally very expensive

Lets say you have made a function which calculates the square of any number. If you try to find the square of a very large number it will take some time before giving the output hence the process is computationally expensive.

If you try to find the square 4 times each time there will be computation performed before generating the output .This is where the role of memoization comes in. Lets say we performed the square of 300000 one time .The memoization or we can say caching means that storing the result the first time such that on every consequent function call instead of performing the operation again we just return the previously computed value.

The concept of memoization is used in the useMemo hook

The syntax of the useMemo hook goes like this:

image.png

Hence the useMemo function is similiar in syntax to the useEffect function and has 2 paramters: 1)A function which returns a value 2)A dependency array which contains the values and if any of the value changes the useMemo function is called again

If the dependency array is blank then the useMemo is only called once and the value it returns remains the same

image.png

One can argue that the same task can be done by just using a simple variable inside the function

Like this:

image.png

But the difference is that useMemo only returns the result either one time or every time the dependency array elements changes.

And at the same time the value of dhruv2 is assigned on every render

image.png

image.png

This is another example and here also there is a slow function which is getting executed hence if the value of the number is same it just returns the memoized value and doesn't compute the value again

The useCallback hook is pretty much the same thing as useMemo with a slight difference

Let us see an example to know the difference:

image.png

From the above example we can notice that useMemo returns a value and useCallback returns a function and on calling the function the value is returned. Thats it thats the only difference

More from this blog

Dhruv's Web development journey

64 posts