Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
How to Memoize with React.useMemo() ?
Next article icon

How to Memoize with React.useMemo() ?

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

React provides a powerful tool for optimizing performance, the useMemo() hook. In this article, we'll delve into how useMemo() works, its benefits, and practical examples of how to manipulate it effectively in your React applications.

Table of Content

  • Understanding useMemo() Hook in React
  • Benefits of useMemo() Hook in React
  • Example of memoizing with useMemo Hook in React
  • Conclusion

Understanding useMemo() Hook in React:

The useMemo() hook is used to memoize the result of a function computation, ensuring that the computation is only re-executed when its dependencies change. This can significantly improve performance by preventing unnecessary recalculations, particularly in scenarios where expensive computations are involved.

Benefits of useMemo() Hook in React:

  • Performance Optimization: By memoizing expensive function results, useMemo() reduces unnecessary re-renders and computations, thereby improving overall application performance.
  • Preventing Unnecessary Work: useMemo() ensures that expensive computations are only performed when necessary, optimizing the utilization of resources and reducing unnecessary work.
  • Enhanced Responsiveness: With useMemo(), React components can respond more quickly to user interactions and data changes, resulting in a smoother user experience.

Example of memoizing with useMemo Hook in React

Example 1: Optimizing Complex Calculations:

  • Let's suppose you have a user interface where you enter a number, and it gets doubled and displayed. Plus, the background color changes with a theme switch.
  • Now, if doubling the number takes a hefty 2 seconds, each time you tweak the input, there's a frustrating 2-second lag due to the slow calculation.
  • But here's the kicker: even changing the theme, which has nothing to do with the number, triggers another 2-second delay because it causes a rerender.
JavaScript
import React, { useState } from "react";  export const Check = () => {     const [state, setState] = useState(0);     const [theme, setTheme] = useState(true);      const slowFunction = (num) => {         for (var i = 0; i < 1000000000; i++) { }         return num * 2;     };      const doubleState = slowFunction(state);      return (         <div className="simple-div">             <center>                 <div>                     <input onChange={(e) =>                         setState(e.target.value)} />                 </div>                 <div style={{                     backgroundColor: theme ? "green" : "white"                 }}>                     <b>Value without memoizing: {doubleState}</b>                 </div>                 <button onClick={() =>                     setTheme((prev) => !prev)}>                     Change Theme                 </button>             </center>         </div>     ); }; 

Output:

gfg1
Performance issue without useMemo()

This problem can be fixed using useMemo() function which will alow us to Memoize the doubling function. This means it only recalculates when you change the input, skipping unnecessary delays from unrelated changes like theme shifts.

JavaScript
import React, { useState, useMemo } from "react";  export const App = () => {     const [state, setState] = useState(0);     const [theme, setTheme] = useState(true);      const slowFunction = (num) => {         for (var i = 0; i < 1000000000; i++) { }         return num * 2;     };     const doubleState = useMemo(() => {         return slowFunction(state);     }, [state]);      return (         <div className="simple-div">             <center>                 <div>                     <input onChange={(e) =>                         setState(e.target.value)} />                 </div>                 <div style={{                     backgroundColor: theme ? "green" : "white"                 }}>                     <b>Value without memoizing: {doubleState}</b>                 </div>                 <button onClick={() =>                     setTheme((prev) => !prev)}>                     Change Theme                 </button>             </center>         </div>     ); }; 

Output:

gfg2
Performance improved using useMemo()


Example 2: Optimize Complex Calculations within Render Props or Higher-order Components using useMemo():

  • Let's accomplish the same task using Higher order functions (HOF). In this approach, we're using withMemoizedCalculation, which uses currying.
  • We first call complexResult, then pass its result to ComponentUsingMemoizedCalculation. However, since complexResult takes a long time to compute, it affects the theme state, as shown in the output below.
JavaScript
import React, { useState } from "react";  const withNonMemoizedCalculation = (calculateFn) =>     (WrappedComponent) => {         return function WithNonMemoizedCalculation(props) {             const result = calculateFn(props);             return <WrappedComponent result={result}                 {...props} />;         };     };  const complexResult = (props) => {     for (let i = 0; i < 1000000000; i++) { }     return props.value * 2; };  const ComponentUsingCalculation = ({ result, theme }) => {     return (         <b style={{ backgroundColor: theme && "green" }}>             Result in HOF: {result}         </b>     ); };  const NonMemoizedComponent = withNonMemoizedCalculation(complexResult)(     ComponentUsingCalculation );  export const App = () => {     const [state, setState] = useState(0);     const [theme, setTheme] = useState(false);     return (         <div className="simple-div">             <center>                 <div>                     <input onChange={(e) =>                         setState(e.target.value)} />                 </div>                 <div>                     <NonMemoizedComponent value={state} theme={theme} />                 </div>                 <button onClick={() =>                     setTheme((prev) => !prev)}>                     Change Theme                 </button>             </center>         </div>     ); };  export default App; 

Output:

hofresult
Performance issue in HOF without useMemo()

Now, let's resolve this by employing useMemo(). We'll memoize the complexResult function based on the state of the props' value, ensuring it doesn't impact the theme state.

JavaScript
import React, { useMemo, useState } from "react";  const withMemoizedCalculation = (calculateFn) =>     (WrappedComponent) => {         return function WithMemoizedCalculation(props) {             const result = useMemo(() => calculateFn(props),                 [props.value]);             return <WrappedComponent result={result}                 {...props} />;         };     };  const complexResult = (props) => {     for (let i = 0; i < 1000000000; i++) { }     return props.value * 2; };  const ComponentUsingMemoizedCalculation = ({ result,     theme }) => {     return (         <b style={{ backgroundColor: theme && "green" }}>             Memoized result in HOF: {result}         </b>     ); };  const MemoizedComponent = withMemoizedCalculation(complexResult)(     ComponentUsingMemoizedCalculation );  export const App = () => {     const [state, setState] = useState(0);     const [theme, setTheme] = useState(false);     return (         <div className="simple-div">             <center>                 <div>                     <input onChange={(e) => setState(e.target.value)} />                 </div>                 <div>                     <MemoizedComponent value={state} theme={theme} />                 </div>                 <button onClick={() =>                     setTheme((prev) => !prev)}>                     Change Theme                 </button>             </center>         </div>     ); };  export default App; 

Output:

hofmemoized

Example 3: Optimize Complex Calculations within Custom Hooks using useMemo(): Let's accomplish the same task using Custom Hooks:

Here, we're utilizing a straightforward custom hook called useExpensiveCalculations. This hook computes a result that takes a considerable amount of time, ultimately impacting the theme state.

JavaScript
import React, { useState } from "react";  const useExpensiveCalculations = (value) => {     const complexResult = () => {         for (let i = 0; i < 1000000000; i++) { }         return value * 2;     };     const result = complexResult();     return { result: result }; };  export const App = () => {     const [state, setState] = useState(0);     const [theme, setTheme] = useState(false);     const { result } = useExpensiveCalculations(state);      return (         <div className="simple-div">             <center>                 <div>                     <input onChange={(e) =>                         setState(e.target.value)} />                 </div>                 <div>                     <b style={{ backgroundColor: theme && "green" }}>                         Memoized Result using custom Hooks: {result}                     </b>                 </div>                 <button onClick={() =>                     setTheme((prev) => !prev)}>                     Change Theme                 </button>             </center>         </div>     ); };  export default App; 

Output:

hookResult
Performance issue without useMemo() in custom hook

Now similarly we will use useMemo() to optimize the hook on re-renders.

JavaScript
import React, { useMemo, useState } from "react";  const useExpensiveCalculations = (value) => {     const complexResult = () => {         for (let i = 0; i < 1000000000; i++) { }         return value * 2;     };      const result = useMemo(() => complexResult(),         [value]);      return { result: result }; };  export const App = () => {     const [state, setState] = useState(0);     const [theme, setTheme] = useState(false);     const { result } = useExpensiveCalculations(state);      return (         <div className="simple-div">             <center>                 <div>                     <input onChange={(e) =>                         setState(e.target.value)} />                 </div>                 <div>                     <b style={{ backgroundColor: theme && "green" }}>                         Memoized Result using custom Hooks: {result}                     </b>                 </div>                 <button onClick={() =>                     setTheme((prev) => !prev)}                 >Change Theme                 </button>             </center>         </div>     ); };  export default App; 

Output:

hookMemoized
Performance improved using useMemo() in custom hook

Conclusion:

useMemo() is a powerful tool for optimizing performance in React applications by memoizing expensive function results. By leveraging useMemo(), you can prevent unnecessary re-renders and computations, resulting in a smoother and more responsive user experience. Whether you're computing Fibonacci numbers, filtering lists, or performing other computationally intensive tasks, useMemo() can be a valuable ally in your quest for performance optimization in React.



Next Article
How to Memoize with React.useMemo() ?

B

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

Similar Reads

    State Management with useState Hook in React
    useState is a built-in hook that empowers functional components to manage state directly, eliminating the need for class-based components or external state management libraries for simple use cases. It provides an easy mechanism to track dynamic data within a component, enabling it to React to user
    3 min read
    ReactJS useMemo Hook
    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.Syntaxconst memoizedValue = useMemo(
    3 min read
    When to use React.memo() over useMemo() & vice-versa ?
    React provides us with powerful tools to optimize the performance of our applications. Two such tools are `React.memo()` and `useMemo()`, which serve similar yet distinct purposes. In this article, we'll explore when to use `React.memo()` over `useMemo()` and vice versa, along with syntax and code e
    4 min read
    Effect Management with useEffect Hook in React
    useEffect serves as a foundational tool in React development, enabling developers to orchestrate side effects within functional components systematically. It facilitates the management of asynchronous tasks, such as data fetching and DOM manipulation, enhancing code organization and maintainability.
    3 min read
    Implementation of React.memo() and useMemo() in React
    React.memo allows functional component to have same optimization as Pure Component provides for class-based components. useMemo is for memoizing function's calls inside functional component. What is React.memo() ?React.memo() is a higher-order component (HOC) provided by React that memoizes function
    3 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