DEV Community

Sibusiso Massango
Sibusiso Massango

Posted on

How useMemo and useCallback hooks work?

The useMemo and useCallback hooks are almost the same but designed and developed for different reasons. The implementation is the same they both expect a function and array of dependencies.

Implementation example
useMemo(()=>{},[])
useCallback(()=>{},[])
The above code do look similar but serves different purposes.

Difference between useMemo and useCallback

  • useMemo calls it's function and return the memoized results while useCallback return it's memoized function when dependencies changes.
  • useMemo only compute when there was a change in dependencies and return memoized results.

What is Memoization?
Memoization in javascript is an optimisation technique, to reduce the complexity of the application, runtime of the application, and proper utilisation of resources (Time and Memory).

By understanding how to use this two hooks properly it will help improving your applications performance.

How does useMemo() work in react?

const memoizedValue = useMemo(function,dependencies)

On an initial rendering useMemo invokes the function, memoize the calculated result and then returns it to the component.
If the there's no change on dependencies during the next rendering, then useMemo will not invoke the function, but it will returns the memoize value.

How does useCallback() work in react?

const memoizedFunction = useMemo(function,dependencies)

React useCallback Hook returns a memoized callback function. Think of memoization as caching a value so that it does not need to be recalculated. This allows us to isolate resource intensive functions so that they will not automatically run on every render, but only run when the was a change in dependencies.

In Conclusion

Understanding how this hooks should help developers to implement them in a correct way, to ensure applications are as optimised as possible. This will also help to avoid creating or running functions every render.

Top comments (0)