MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
The useMemo Hook and Expensive Computations0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
8.1React Re-render Rules and Profiling Bottlenecks8.2Memoizing Components with React memo8.3The useCallback Hook and Stabilizing Callback Props8.4The useMemo Hook and Expensive Computations
HomeTutorialsReact.js for IntermediateThe useMemo Hook and Expensive Computations
Extracting Reusable Business Logic into Custom Hooks

The useMemo Hook and Expensive Computations

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. What is useMemo?

While useCallback caches a function definition, useMemo caches the result of an expensive computation.

$$\text{CachedResult} = \text{useMemo}(\text{calculateValue}, \text{dependencies})$$

On initial render, useMemo calls your calculation function and stores the result. On subsequent renders, React checks if the dependencies have changed:

  • If dependencies are unchanged, React returns the cached result without running the calculation again.
  • If dependencies have changed, React re-executes the calculation, stores the new result, and returns it.
1Render 1:
2useMemo(() => expensiveCalculation(data), [data]) ──► Runs calculation (takes 80ms) ──► Returns result
3 
4Render 2 (unrelated state changed, data is same):
5useMemo(...) ──► Returns cached result instantly (takes 0.001ms)!

2. Practical Example: Filtering 10,000 Complex Records

1import React, { useState, useMemo } from 'react';
2 
3// Simulated heavy calculation
4function performComplexAnalytics(transactions, threshold) {
5 console.log('Running heavy analytics calculation...');
6 // Intensive array filtering, grouping, and statistical variance calculation
7 return transactions
8 .filter(t => t.amount >= threshold)
9 .reduce((acc, t) => acc + t.amount, 0);
10}
11 
12export default function AnalyticsDashboard({ transactions }) {
13 const [threshold, setThreshold] = useState(100);
14 const [theme, setTheme] = useState('light');
15 
16 // ✅ useMemo caches the computed total:
17 // When 'theme' changes, this expensive calculation is COMPLETELY SKIPPED!
18 const totalVolume = useMemo(() => {
19 return performComplexAnalytics(transactions, threshold);
20 }, [transactions, threshold]); // Only recompute when transactions or threshold changes!
21 
22 return (
23 <div className={`analytics-box theme-${theme}`}>
24 <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
25 Toggle Dashboard Theme
26 </button>
27 
28 <h3>Analyzed Volume: ${totalVolume.toLocaleString()}</h3>
29
30 <input
31 type="range"
32 min={0}
33 max={1000}
34 value={threshold}
35 onChange={(e) => setThreshold(Number(e.target.value))}
36 />
37 </div>
38 );
39}

3. Difference Between useMemo and useCallback

Engineers often confuse the two hooks:

  • useMemo: Invokes the function and caches its return value (useMemo(() => computeVal(), deps)).
  • useCallback: Caches the function itself without executing it (useCallback(() => doSomething(), deps)).

In fact, useCallback(fn, deps) is simply syntactic sugar for:

1useMemo(() => fn, deps);

4. When Is a Calculation Truly "Expensive"?

Most everyday JavaScript operations (mapping 50 array elements, basic math, string concatenations) execute in fractions of a microsecond. Wrapping them in useMemo adds more overhead than it saves!

How to measure:

Use console.time() or the React DevTools Profiler:

1console.time('filter');
2const results = filterData(items);
3console.timeEnd('filter');

If the calculation takes less than 1ms, memoization is unnecessary. If it takes 10ms or more, wrapping it in useMemo delivers substantial real-world responsiveness gains.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does the useMemo hook cache across component renders?
Question 2
How does useMemo differ from useCallback?
Question 3
When is wrapping a calculation in useMemo genuinely justified?
Question 4
If useMemo(() => computeTotal(items), [items]) has an unchanged items array, what does React do during render?
Question 5
What is the equivalent of useCallback(fn, deps) expressed using useMemo?
Next Lesson

Extracting Reusable Business Logic into Custom Hooks

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
The useCallback Hook and Stabilizing Callback PropsExtracting Reusable Business Logic into Custom Hooks

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext