useMemo vs usecallback in simple terms

akshaysrepo

Akshay S

Posted on January 16, 2023

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
akshaysrepo
Akshay S

Posted on January 16, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About