Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

UseMemo vs useCallback

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
1.975 mins read

Both useMemo and useCallback are hooks in React that are used to optimize performance by memoizing values or functions. They help in avoiding unnecessary recalculations and re-rendering of components.

The working of both in the descriptive manner is mentioned below -

useMemo

The useMemo hook is used to memoize a value, which means it caches the result of a function and returns that cached value until the dependencies change.

It takes two arguments - the first is a function that computes the value, and the second is an array of dependencies. The hook will recompute the value only if any of the dependencies in the array have changed.

import React, { useMemo } from 'react';

function MyComponent({ items }) {
  // 'total' will be recomputed only if 'items' array changes
  const total = useMemo(() => {
    console.log('Calculating total...');
    return items.reduce((acc, item) => acc + item.    price, 0);
  }, [items]);

  return (
    <div>
      <h1>Total: {total}</h1>
    </div>
  );
}

In this example, the total variable will be recalculated only when the items prop changes. If the items prop remains the same, the cached value will be returned, and the expensive calculation inside useMemo won't be executed.

useCallback

The useCallback hook is used to memoize functions, which means it returns a memoized version of the function that only changes if any of its dependencies change. It is particularly useful when passing functions to child components to prevent unnecessary re-renders.

import React, { useState, useCallback } from 'react';

 function MyComponent() {
   const [count, setCount] = useState(0);
 
   // 'handleClick' will be recreated only if 'count' changes
   const handleClick = useCallback(() => {
     console.log('Button clicked');
     setCount(count + 1);
   }, [count]);

   return (
     <div>
       <h1>Count: {count}</h1>
       <button onClick={handleClick}>Increment</button>
     </div>
   );
 }

In this example, the handleClick function will be recreated only when the count state changes. If we didn't use useCallback, the function would be recreated on every render, leading to unnecessary re-renders of child components that receive this function as a prop.

In summary, useMemo is used to memorize a value, and useCallback is used to memorize a function. Both are helpful in optimizing performance and reducing unnecessary calculations and re-renders, but they serve different purposes. Remember to use useMemo when we want to cache a value based on dependencies and useCallback when we want to cache a function based on dependencies.

Library

WEB DEVELOPMENT

Basic

Frontend

Express JS

React

Hello World in ReactJS

Rendering Elements

States and Lifecycles in React JS

Handling Events in React JS

Introduction to JSX

Components and Props in React JS

Conditional Rendering

Lists and Keys in React JS

Introduction to Redux

Types of components (class vs functional)

Using the useEffect hook

Building custom hooks in React JS

Context API in React JS

Forms in React JS

Lifting State Up in React JS

Composition vs Inheritance

Prop drilling in React JS

Introduction to Hooks

Using the useState hook

UseMemo vs useCallback

Backend

Interview Questions

FAANG QUESTIONS

On this page

useMemo

useCallback