Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
ReactJS useEffect Hook
Next article icon

ReactJS useMemo Hook

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The useMemo Hook is a built-in React Hook that helps optimize performance by memoizing the result of a computation and reusing it unless its dependencies change. This prevents expensive computations from being re-executed unnecessarily during component re-renders.

Syntax

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • The first argument is a function that returns the computed value.
  • The second argument is an array of dependencies. When any of these dependencies change, the function gets re-evaluated.

Let’s now see some of the Practical Applications of useMemo

1. Optimizing Expensive Calculations

Let’s take an example where we have an expensive computation that should not be recalculated on every render.

JavaScript
import React, { useState, useMemo } from "react";  function App() {     const [number, setNumber] = useState(0);     const squaredNum = useMemo(() => squareNum(number), [number]);     const [counter, setCounter] = useState(0);     const onChangeHandler = (e) => {         setNumber(e.target.value);     };     const counterHander = () => {         setCounter(counter + 1);     };     return (         <div className="App">             <h1>Welcome to Geeksforgeeks</h1>             <input                 type="number"                 placeholder="Enter a number"                 value={number}                 onChange={onChangeHandler}             ></input>              <div>OUTPUT: {squaredNum}</div>             <button onClick={counterHander}>Counter ++</button>             <div>Counter : {counter}</div>         </div>     ); } function squareNum(number) {     console.log("Squaring will be done!");     return Math.pow(number, 2); } export default App; 

Output

UseMemo2

In this example

  • useState manages number (user input) and counter (button clicks).
  • useMemo caches squareNum(number), recalculating only when number changes.
  • The input field updates the number state when changed.
  • Clicking “Counter ++” increases the counter state.
  • The component displays the input, memoized squared value, and counter.

2. Preventing Unnecessary Re-renders

Sometimes, passing objects or arrays as props to child components can trigger unnecessary re-renders due to reference changes. useMemo can help stabilize such values.

JavaScript
import React, { useState, useMemo } from "react";  function Child({ userInfo }) {     console.log("Child component rendered");     return <p>User: {userInfo.name}</p>; } function Parent() {     const [count, setCount] = useState(0);     const userInfo = useMemo(() => ({ name: "GeeksforGeeks" }), []);     return (         <div>             <p>Count: {count}</p>             <Child userInfo={userInfo} />             <button onClick={() => setCount(count + 1)}>Increment Count</button>         </div>     ); } export default Parent; 

Output

UseMemo

In this example

  • React, useState, and useMemo are imported for state management and optimization.
  • ChildComponent displays userInfo.name and logs renders.
  • ParentComponent memoizes userInfo to prevent re-creation.
  • Clicking the button updates count, re-rendering ParentComponent.
  • ParentComponent displays count, ChildComponent, and the button.

When to Use useMemo?

You should use useMemo when

  • You have expensive calculations that do not need to be re-executed unless certain dependencies change.
  • You are dealing with large data sets and need to optimize performance.
  • You want to prevent unnecessary re-renders of child components by ensuring stable references.

However, avoid overusing useMemo as it can add complexity and memory overhead. Use it only when necessary.

Performance Optimization Using useMemo

Using useMemo correctly can significantly enhance the performance of React applications. However, improper usage may lead to unnecessary memory usage and increased complexity. Here are some key considerations:

  • Avoid using useMemo for trivial calculations: If the computation is lightweight, memoization may introduce unnecessary complexity.
  • Use it for expensive calculations: Tasks such as filtering large datasets or performing intensive calculations can benefit from useMemo.
  • Stabilize object and array references: When passing objects or arrays to child components, useMemo helps maintain the same reference and prevents unnecessary re-renders.
  • Measure before optimizing: Always analyze your app’s performance using React DevTools or profiling tools before introducing useMemo.

Key Takeaways

  • Performance optimization: useMemo helps optimize expensive calculations.
  • Prevents unnecessary re-renders: Helps in stabilizing reference values passed as props.
  • Use it wisely: Overuse of useMemo can lead to unnecessary complexity.


Next Article
ReactJS useEffect Hook

A

ashisholism
Improve
Article Tags :
  • ReactJS
  • Web Technologies
  • React-Hooks

Similar Reads

  • ReactJS useId Hook
    React useId Hook is introduced for the ReactJS versions above 18. This hook generates unique IDs i.e, returns a string that is stable across both the server and the client sides. Prerequisite: Introduction and installation of ReactJSReact Hooks Syntax: const id = useId() Creating React Application:
    3 min read
  • ReactJS useEffect Hook
    The useEffect hook is one of the most commonly used hooks in ReactJS used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. What is
    5 min read
  • ReactJS useParams Hook
    In ReactJS, when building single-page applications (SPAs) with dynamic routing, you often need to access dynamic data from the URL. For example, in a blog application, the URL will change depending on the post being viewed, like /post/:id. The useParams hook, provided by the react-router-dom package
    3 min read
  • ReactJS useSelect hook
    The useSelect is a custom hook provided by the Rooks package for React. It is a list selection hook that helps select values from a list. Arguments: list: It is of the type array which describes the list of items for the selection. The default value is undefined.initialIndex -It is of the type numbe
    2 min read
  • ReactJS useContext Hook
    In React Applications, sometimes managing state across deeply nested components can become very difficult. The useContext hook offers a simple and efficient solution to share state between components without the need for prop drilling. What is useContext Hook?The useContext hook in React allows comp
    5 min read
  • ReactJS useReducer Hook
    The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently. Syntax const [state, dispatch] = useReduce
    5 min read
  • React useState Hook
    The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
    5 min read
  • ReactJS useTimeout Custom Hook
    We often run into timeouts when building applications in React. setTimeout() executes code after a specified period only once. Usually, we don't need to worry about clearing out our timeouts when using setTimeout. However, it can be challenging to use the setTimeout method in React because we might
    5 min read
  • ReactJs useDebugValue Hook
    React useDebugValue Hook is introduced for the ReactJs versions above 18. React useDebugValue Hook helps developers debug custom hooks in React Developer Tools by adding additional information and labels to those hooks. Prerequisite:ReactJSReact Developer ToolsReact HooksReact Custom HooksApproach:T
    2 min read
  • ReactJS useLayoutEffect Hook
    The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences