DEV Community

Akshay S
Akshay S

Posted on

useMemo vs usecallback in simple terms

When building a React application, two hooks that are commonly used for performance optimization are useMemo and useCallback.

useMemo is a hook that allows you to cache the result of a expensive computation and only re-evaluate it when one of the dependencies has changed. This can greatly improve the performance of your application by avoiding unnecessary re-renders.

useCallback is similar to useMemo, but it is used to cache the reference to a function, instead of caching the result of a computation. This is useful when passing a function down as a prop to a child component and you want to avoid re-creating the function on every render.

In short, useMemo is used to cache the result of a computation and useCallback is used to cache the reference to a function. Both can help improve the performance of your React application by avoiding unnecessary re-renders.

import { useMemo, useCallback } from 'react';

function MyComponent({ data }) {
  const memoizedData = useMemo(() => {
    // perform expensive computation on data
    return data.map(item => item * 2);
  }, [data]);

  const handleClick = useCallback(() => {
    console.log(memoizedData);
  }, [memoizedData]);

  return (
    <div>
      <button onClick={handleClick}>Log Data</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, useMemo is used to memoize the result of an expensive computation performed on the data prop. This means that the computation will only be performed again if the data prop changes.

useCallback is then used to create a callback function that will only change if the memoizedData value changes. This is useful when passing the callback as a prop to a child component, as it will help prevent unnecessary re-renders of the child component.

Top comments (0)