Skip to content

React JS: useMemo vs memo - A Comprehensive Guide

Haikel Fazzani Haikel Fazzani
2025-01-17

As a React developer, optimizing performance is crucial. Two tools that help with this are useMemo and memo. Let’s break them down with easy examples.

What is useMemo?

useMemo is a React Hook that remembers (or “memoizes”) the result of a calculation. This means it stores the result and only recalculates it when certain values (dependencies) change. This is great for expensive calculations that don’t need to be repeated every time a component re-renders.

Simple Example:

import React, { useMemo } from 'react';

function ExpensiveCalculation({ a, b }) {
  // Only recalculate when 'a' or 'b' changes
  const result = useMemo(() => {
    console.log('Calculating...');
    return a * b; // Expensive calculation
  }, [a, b]);

  return <div>Result: {result}</div>;
}

function App() {
  const [count, setCount] = React.useState(0);
  
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Re-render ({count})</button>
      <ExpensiveCalculation a={5} b={10} />
    </div>
  );
}

What happens here?


What is memo?

memo is a higher-order component that prevents a component from re-rendering if its props haven’t changed. It’s like a “smart” component that only updates when necessary.

Simple Example:

import React, { memo } from 'react';

const Greeting = memo(({ name }) => {
  console.log('Greeting rendered!');
  return <div>Hello, {name}!</div>;
});

function App() {
  const [count, setCount] = React.useState(0);
  
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Re-render ({count})</button>
      <Greeting name="Alice" />
    </div>
  );
}

What happens here?


useMemo vs memo: Key Differences

FeatureuseMemomemo
What it doesMemoizes values (e.g., calculations)Memoizes components (prevents re-renders)
How it worksUses a dependency array ([a, b])Uses prop comparison
Best forExpensive calculationsComponents with stable props

When to Use useMemo

  1. Slow calculations: If a computation takes time (e.g., filtering a big list), use useMemo to avoid repeating it.
  2. Derived data: If you compute something from props/state (e.g., totalPrice = items.reduce(...)), useMemo can help.

Example:

const total = useMemo(() => {
  return items.reduce((sum, item) => sum + item.price, 0);
}, [items]); // Only recalculate if 'items' changes

When to Use memo

  1. Stable props: If a child component receives the same props repeatedly, memo can skip re-rendering.
  2. Performance issues: If a component is slow to render, memo might help.

Example:

const UserCard = memo(({ user }) => {
  return <div>{user.name}</div>;
});

// Only re-renders if 'user' changes
<UserCard user={{ id: 1, name: "Bob" }} />

Common Mistakes & Tips

1. Don’t overuse them!

2. memo and objects/arrays

3. Missing dependencies in useMemo


Combining useMemo and memo

You can use both together for maximum optimization!

import React, { useMemo, memo } from 'react';

const Calculator = memo(({ a, b }) => {
  const result = useMemo(() => {
    console.log('Calculating...');
    return a + b;
  }, [a, b]);

  return <div>Result: {result}</div>;
});

function App() {
  const [count, setCount] = React.useState(0);
  
  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Re-render ({count})</button>
      <Calculator a={3} b={7} />
    </div>
  );
}

What happens here?


FAQs

Q1: What’s the difference between useMemo and useCallback?

Q2: Can I use memo with class components?

Q3: Does useMemo prevent re-renders?

Q4: When should I avoid useMemo?


Conclusion


Reading Further


Happy coding! 🚀


React js useMemo memo React performance optimization React hooks React memoization

More Insights.