DEV Community

Akshay S
Akshay S

Posted on

1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay