DEV Community

Pramod
Pramod

Posted on

usememo & useCallback hook

useMemo and useCallback are two important hooks provided by React to optimize performance in functional components by memoizing values and callbacks respectively.
1.useMemo:
useMemo is used to memoize the result of a function so that the function is only re-executed when one of its dependencies changes.
Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a,

b), [a, b]);
Example:
const memoizedResult = useMemo(() => {
return computeExpensiveValue(a, b);
}, [a, b]);
2.useCallback:
useCallback is used to memoize callbacks so that they are only recreated if one of their dependencies changes.
Syntax:
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Example:
const memoizedCallback = useCallback(() => {
handleClick(id);
}, [id]);
In this example, handleClick will only be recreated if id changes.
These hooks are especially useful when dealing with expensive computations or passing callbacks to child components, helping to prevent unnecessary re-renders and optimize the performance of your React application.

Top comments (0)