Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Optimizing Performance with useMemo

Learn how to memoize expensive calculations using the useMemo hook.

jiocoder TeamUpdated Jun 6, 20261 min readReact
Optimizing Performance with useMemo

What is useMemo?#

useMemo is a React hook that memoizes the result of a computation. It only recalculates when its dependencies change, helping optimize expensive operations.

Basic Syntax#

Code
import { useMemo } from 'react';

const memoizedValue = useMemo(() => {
  return expensiveComputation(a, b);
}, [a, b]);

Example: Expensive Calculation#

Code
function ExpensiveComponent({ items, filter }) {
  const filteredItems = useMemo(() => {
    return items.filter(item => 
      item.name.toLowerCase().includes(filter.toLowerCase())
    );
  }, [items, filter]);
  
  return (
    <ul>
      {filteredItems.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

When to Use useMemo#

  • Expensive calculations that don't need to run on every render
  • Referential equality for objects/arrays passed as props
  • Preventing unnecessary child re-renders

When NOT to Use useMemo#

  • Simple calculations (overhead might be worse)
  • Every value needs to be memoized (premature optimization)
  • Dependencies change frequently

Best Practices#

  • Profile first - don't optimize prematurely
  • Include all dependencies in the dependency array
  • Use for expensive operations only
  • Combine with React.memo for component memoization

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment