1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usememo Hook
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
19Mins
40Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Usememo Hook

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
19Mins
40Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useMemo Hook

Overview

During a React re-render, the entire component function runs from top to bottom. If you have a slow, CPU-intensive mathematical calculation (like filtering a massive array of 100,000 items, or running a cryptographic hash), that calculation will run every single time the component re-renders. If the user is typing in a text box, the calculation runs on every keystroke, freezing the browser.

The `useMemo` hook solves this by 'memoizing' (caching) the result of a calculation.

You pass useMemo a function that performs the heavy math, and a Dependency Array. React will run the math once, cache the result, and return it. On subsequent renders, React checks the dependency array. If the dependencies haven't changed, React skips the math entirely and instantly returns the cached result.

Syntax

Caching an Expensive Calculation
javascript
import { useState, useMemo } from 'react';

function DataAnalyzer({ rawData }) {
  const [theme, setTheme] = useState('dark');

  // 1. Without useMemo, this heavy loop runs every time 'theme' is toggled!
  // const processedStats = runHeavyCalculations(rawData); 

  // 2. With useMemo, the calculation ONLY runs when 'rawData' changes.
  // Toggling the theme instantly bypasses the math and uses the cached data.
  const processedStats = useMemo(() => {
    console.log("Running 500ms calculation...");
    return runHeavyCalculations(rawData);
  }, [rawData]); // Re-run ONLY if rawData changes

  return (
    <div className={theme}>
      <button onClick={() => setTheme(t => t === 'dark' ? 'light' : 'dark')}>
        Toggle Theme
      </button>
      <StatsDisplay stats={processedStats} />
    </div>
  );
}

Common Pitfalls

  • Using useMemo for cheap operations: Do not use useMemo for simple operations like array.map() on 10 items or basic string concatenations. Calling the useMemo hook and allocating the cache memory actually has a baseline performance cost. Caching cheap math is slower than just running the cheap math.

Interview Questions

What is the difference between useEffect and useMemo?

useEffect is for executing side effects (like API calls) after the render is completely finished. useMemo is for caching the result of a mathematical calculation during the render phase so that the render itself happens faster.

How does useMemo help fix React.memo components that are breaking?

Because React.memo does a shallow comparison, passing a newly created object like config={{ color: 'red' }} will cause the memoized child to re-render (since {} creates a new memory reference every render). You can use useMemo to cache the object itself (const config = useMemo(() => ({ color: 'red' }), [])), preserving its exact memory reference and allowing React.memo to work properly.

Real-World Example

Preserving Object References for Context: This is arguably the most important use case for useMemo in modern React. It is absolutely mandatory to memoize object values passed into Context Providers to prevent massive, app-wide render cascades.

example
javascript
function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  // If we pass an inline object to the Context Provider:
  // value={{ user, setUser }}
  // EVERY consumer of this context will re-render whenever AuthProvider re-renders,
  // because the object {} is technically a new reference every time.

  // The Fix: Cache the object reference using useMemo!
  const contextValue = useMemo(() => {
    return { user, setUser };
  }, [user]); // Only recreate the object if 'user' actually changes

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  );
}

Check Your Knowledge

Test your understanding of useMemo Hook with these quick questions.

Question 1

What does the `useMemo` hook primarily return?

Question 2

When should you definitely NOT use `useMemo`?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

useMemo Hook

Overview

During a React re-render, the entire component function runs from top to bottom. If you have a slow, CPU-intensive mathematical calculation (like filtering a massive array of 100,000 items, or running a cryptographic hash), that calculation will run every single time the component re-renders. If the user is typing in a text box, the calculation runs on every keystroke, freezing the browser.

The `useMemo` hook solves this by 'memoizing' (caching) the result of a calculation.

You pass useMemo a function that performs the heavy math, and a Dependency Array. React will run the math once, cache the result, and return it. On subsequent renders, React checks the dependency array. If the dependencies haven't changed, React skips the math entirely and instantly returns the cached result.

Syntax

Caching an Expensive Calculation
javascript
import { useState, useMemo } from 'react';

function DataAnalyzer({ rawData }) {
  const [theme, setTheme] = useState('dark');

  // 1. Without useMemo, this heavy loop runs every time 'theme' is toggled!
  // const processedStats = runHeavyCalculations(rawData); 

  // 2. With useMemo, the calculation ONLY runs when 'rawData' changes.
  // Toggling the theme instantly bypasses the math and uses the cached data.
  const processedStats = useMemo(() => {
    console.log("Running 500ms calculation...");
    return runHeavyCalculations(rawData);
  }, [rawData]); // Re-run ONLY if rawData changes

  return (
    <div className={theme}>
      <button onClick={() => setTheme(t => t === 'dark' ? 'light' : 'dark')}>
        Toggle Theme
      </button>
      <StatsDisplay stats={processedStats} />
    </div>
  );
}

Common Pitfalls

  • Using useMemo for cheap operations: Do not use useMemo for simple operations like array.map() on 10 items or basic string concatenations. Calling the useMemo hook and allocating the cache memory actually has a baseline performance cost. Caching cheap math is slower than just running the cheap math.

Interview Questions

What is the difference between useEffect and useMemo?

useEffect is for executing side effects (like API calls) after the render is completely finished. useMemo is for caching the result of a mathematical calculation during the render phase so that the render itself happens faster.

How does useMemo help fix React.memo components that are breaking?

Because React.memo does a shallow comparison, passing a newly created object like config={{ color: 'red' }} will cause the memoized child to re-render (since {} creates a new memory reference every render). You can use useMemo to cache the object itself (const config = useMemo(() => ({ color: 'red' }), [])), preserving its exact memory reference and allowing React.memo to work properly.

Real-World Example

Preserving Object References for Context: This is arguably the most important use case for useMemo in modern React. It is absolutely mandatory to memoize object values passed into Context Providers to prevent massive, app-wide render cascades.

example
javascript
function AuthProvider({ children }) {
  const [user, setUser] = useState(null);

  // If we pass an inline object to the Context Provider:
  // value={{ user, setUser }}
  // EVERY consumer of this context will re-render whenever AuthProvider re-renders,
  // because the object {} is technically a new reference every time.

  // The Fix: Cache the object reference using useMemo!
  const contextValue = useMemo(() => {
    return { user, setUser };
  }, [user]); // Only recreate the object if 'user' actually changes

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  );
}

Check Your Knowledge

Test your understanding of useMemo Hook with these quick questions.

Question 1

What does the `useMemo` hook primarily return?

Question 2

When should you definitely NOT use `useMemo`?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A