const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Returns a memoized value.
useMemo is very similar to useCallback Hook(please visit the provided link to know more about useCallback : https://hashnode.com/edit/cldmtqk0m00000ald60j3fk5z), the major difference is, in useCallback it caches the instance of a function itself and returns it, but in case of useMemo it caches the computed value and returns it, in useMemo we pass a function and dependencies, so useMemo will help us here to avoid recomputation of function again, if no dependency changes in component re-render, so if the function call is very expensive(takes long time) so here it becomes very useful for performance optimization.
Lets understand the useMemo Hook with the help of sample code as illustrated below:
import { useMemo } from 'react'; // here we are importing useMemo in order to use it inside the functional component.
function TodoList({ todos, tab }) {
// below we have passed the filterTodos function and also the required dependencies, in initial render it will make a call to filterTodos function, but after that in component re-render it will return you the cached computed value and will never call the function again until any of its dependency changes.
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab]
);
// ...
}
// Article ends here...
Thanks, Happy coding