Member-only story

‘useMemo’ vs ‘useCallback’

Sumit kumar Singh
2 min readMar 19, 2023

useMemo and useCallback are React hooks that can help optimize the performance of your React components by memoizing values and functions. Although they are similar in some ways, they have different use cases and implementation details. Here's an in-depth explanation of useMemo and useCallback:

useMemo

useMemo is used to memoize a value that is computationally expensive to calculate. The hook takes a function that returns a value and an array of dependencies as input. The function is only called when one of the dependencies changes.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

In this example, computeExpensiveValue is a function that returns a value based on the inputs a and b. The memoized value is computed when either a or b changes. If neither a nor b changes memoizedValue is returned from the cache.

useMemo is useful when you have a computationally expensive function that needs to be called often, but you don't want to recompute it every time the component is re-rendered.

useCallback

useCallback is used to memoize a function that is passed as a prop to child components. The hook takes a function and an array of dependencies as input. The memoized function is only recreated when one of the dependencies…

--

--

Sumit kumar Singh
Sumit kumar Singh

Written by Sumit kumar Singh

YouTube: https://shorturl.at/8zZ4B Topmate: https://topmate.io/sumit_kr_singh 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks

No responses yet