Give an example of optimization using useMemo in React

Optimize expensive calculations in React using useMemo to memoize computed values and avoid unnecessary recalculations.

intermediatePerformance optimizationreactuseMemoperformanceoptimization
Published: 10/26/2025
Updated: 10/26/2025

Question

Give an example of optimization using useMemo in React.


Answer

useMemo memoizes a computed value between renders.
It’s ideal for optimizing expensive calculations that depend on specific inputs.

import { useState, useMemo } from 'react';

function FibonacciCalculator() {
  const [num, setNum] = useState(10);
  const [theme, setTheme] = useState('light');

  const fib = useMemo(() => {
    console.log('Calculating Fibonacci...');
    function fibonacci(n) {
      return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    }
    return fibonacci(num);
  }, [num]);

  return (
    <div className={theme}>
      <h3>
        Fibonacci of {num}: {fib}
      </h3>
      <button onClick={() => setNum(num + 1)}>+</button>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme
      </button>
    </div>
  );
}

✅ Without useMemo, the expensive calculation runs every time the theme toggles.

✅ With useMemo, it only recalculates when num changes.

Real-World Example

  • Filtering or sorting large lists
  • Derived data calculations
  • Expensive mathematical operations

Quick Practice

Build a component that filters a product list using useMemo to prevent unnecessary re-computation.

Summary

Use useMemo to cache computed values between renders for better performance.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

When should I use useMemo?

When you have expensive calculations that don't need to re-run on every render.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.