Differences Between useMemo, useCallback, and memo in React With Example

ยท

2 min read

Differences Between useMemo, useCallback, and memo in React With Example

Certainly! Let's explore the differences between useMemo, useCallback, and memo in React:

  1. useMemo:

    • useMemo is a hook used to memoize the result of a computation. It allows you to optimize expensive calculations by caching the computed value and only recomputing it when the dependencies change.

    • It takes a function and an array of dependencies as arguments. The function is executed during rendering, and the result is memoized and returned. The memoized value is recalculated only if any of the dependencies change.

    • It is typically used for performance optimization when you have a costly computation that you want to avoid performing on every render.

    • Example:

    const memoizedValue = useMemo(() => expensiveComputation(a, b), [a, b]);
  1. useCallback:

    • useCallback is a hook used to memoize a function instance. It returns a memoized version of the function that only changes if one of the dependencies has changed.

    • It is useful when passing callbacks to child components, as it ensures that the child components do not unnecessarily re-render when the callback reference changes.

    • It takes a function and an array of dependencies as arguments. The function is memoized, and the memoized function is returned.

    • Example:

    const memoizedCallback = useCallback(() => {
      // callback logic
    }, [dependency]);
  1. memo:

    • memo is a higher-order component (HOC) provided by React. It is used to wrap a functional component and optimize its rendering by preventing unnecessary re-renders.

    • It compares the props passed to the component and decides whether to re-render it based on shallow equality checks. If the props have not changed, the component is not re-rendered.

    • It is useful when you have a component that receives the same props but does not need to re-render if the props haven't changed.

    • Example:

    const MyComponent = React.memo((props) => {
      // component logic
    });

In summary, useMemo and useCallback are hooks used for performance optimization by memoizing values and function instances, respectively. They ensure that the memoized value or function reference is only recalculated when the dependencies change. On the other hand, memo is an HOC used to optimize functional components by preventing unnecessary re-renders based on shallow prop equality checks.

Buy Me A Coffee

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย