← Back to Articles         
useMemo in React

useMemo in React

Published on 15 Nov 2026 38 min read React
React Fundamentals

1. What is useMemo in React?

useMemo is a React Hook used to remember the result of a calculation so React does not have to perform that calculation again on every render.

In simple words:

useMemo = “Calculate this value again only when its dependencies change.”

Basic syntax:

const memoizedValue = useMemo(() => {
    return someCalculation();
}, [dependencies]);

For example:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

React calculates total when price or quantity changes.

If the component renders again for some other reason, React can reuse the previously calculated total.


2. Why do we need useMemo?

Consider this component:

function Product() {
    const [count, setCount] = useState(0);
    const [price, setPrice] = useState(100);

    const total = price * 10;

    return (
        <>
            <p>Count: {count}</p>
            <p>Total: {total}</p>

            <button onClick={() => setCount(count + 1)}>
                Increase Count
            </button>
        </>
    );
}

When count changes:

count changes
     ↓
Component renders again
     ↓
price * 10 is calculated again
     ↓
UI is updated

For a simple calculation such as:

price * 10

this is completely fine.

There is no need for useMemo.

But imagine:

const filteredProducts = products
    .filter(...)
    .sort(...)
    .map(...);

and there are 10,000 products.

Now the calculation could be expensive.

This is where useMemo can help.


3. The main purpose of useMemo

Think of it like this:

Without useMemo

Render
  ↓
Run calculation
  ↓
Render
  ↓
Run calculation again
  ↓
Render
  ↓
Run calculation again

With useMemo

Render
  ↓
Run calculation
  ↓
Store result

Next render
  ↓
Did dependencies change?
  ↓
NO
  ↓
Reuse stored result

If dependencies change:

price changes
     ↓
Dependencies changed
     ↓
Run calculation again
     ↓
Store new result

4. Basic usage

Simple example

import { useMemo, useState } from "react";

function App() {
    const [count, setCount] = useState(0);
    const [price, setPrice] = useState(100);

    const total = useMemo(() => {
        console.log("Calculating total...");

        return price * 10;
    }, [price]);

    return (
        <div>
            <h2>Count: {count}</h2>
            <h2>Total: ₹{total}</h2>

            <button onClick={() => setCount(count + 1)}>
                Increase Count
            </button>

            <button onClick={() => setPrice(price + 50)}>
                Increase Price
            </button>
        </div>
    );
}

What happens?

Initially:

price = 100
count = 0

Calculating total...
total = 1000

Click:

Increase Count

Now:

count = 1
price = 100

The component renders again.

But:

price has not changed

Therefore:

useMemo
   ↓
price unchanged
   ↓
reuse total = 1000

The calculation doesn't need to run again.

If you click:

Increase Price

then:

price = 150

The dependency changed:

[price]
   ↓
price changed
   ↓
calculate again
   ↓
total = 1500

5. The most important thing to understand

useMemo does not prevent a component from rendering.

This is extremely important.

Suppose:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

If count changes:

count changes
     ↓
Component renders
     ↓
useMemo checks dependencies
     ↓
price unchanged
quantity unchanged
     ↓
Reuse previous total

The component still rendered.

Only the calculation was skipped.

So:

useMemo ≠ prevent re-render

Instead:

useMemo = avoid repeating an expensive calculation

6. How does useMemo work?

The basic flow is:

Component renders
       ↓
useMemo executes
       ↓
Check dependencies
       ↓
┌──────────────────────┐
│ Dependencies changed?│
└──────────────────────┘
       ↓
   ┌───┴───┐
   │       │
  YES      NO
   ↓       ↓
Calculate  Return cached
again      value
   ↓
Store new value

For example:

const result = useMemo(() => {
    return expensiveCalculation(data);
}, [data]);

React remembers:

Previous data
Previous result

On the next render, React checks:

Has data changed?

If not:

return previous result

7. What does "memoized value" mean?

You may hear the term memoization.

Memoization simply means:

Remember the result of a calculation so that the same calculation does not have to be performed again.

For example:

Input: 10

Calculation:
10 × 100

Result:
1000

Instead of repeatedly calculating:

10 × 100
10 × 100
10 × 100
10 × 100

we remember:

10 → 1000

React's useMemo applies this idea to values calculated inside components.


8. Scenario 1 — Expensive calculation

This is the most important use case.

Suppose:

function expensiveCalculation(num: number) {
    console.log("Expensive calculation running...");

    let result = 0;

    for (let i = 0; i < 100000000; i++) {
        result += num;
    }

    return result;
}

Using it directly:

const result = expensiveCalculation(number);

Every render executes it.

Using useMemo:

const result = useMemo(() => {
    return expensiveCalculation(number);
}, [number]);

Now:

number unchanged
       ↓
Reuse previous result

instead of:

number unchanged
       ↓
Run expensiveCalculation()
again

9. Scenario 2 — Filtering a large list

This is a very common real-world scenario.

Imagine:

const products = [
    // thousands of products
];

You want to filter them:

const filteredProducts = products.filter(product =>
    product.name.toLowerCase().includes(search)
);

Without useMemo, this filtering happens whenever the component renders.

With useMemo:

const filteredProducts = useMemo(() => {
    return products.filter(product =>
        product.name.toLowerCase().includes(search.toLowerCase())
    );
}, [products, search]);

Now React recalculates only when:

products changes
OR
search changes

Example

products = 10,000 items
search = "laptop"

filter → 500 products

If another state changes:

setCount(count + 1);

the component renders.

But:

products = same
search = same

Therefore:

useMemo → reuse 500 products

10. Scenario 3 — Sorting data

Sorting can also be expensive for large datasets.

Without useMemo:

const sortedProducts = products.sort(...);

With useMemo:

const sortedProducts = useMemo(() => {
    return [...products].sort((a, b) => a.price - b.price);
}, [products]);

The important part is:

[...products]

instead of:

products.sort(...)

because .sort() modifies the original array.

React applications generally work better when state is treated as immutable.


11. Scenario 4 — Filtering + sorting

Real applications often combine operations.

const filteredAndSortedProducts = useMemo(() => {
    return products
        .filter(product =>
            product.name
                .toLowerCase()
                .includes(search.toLowerCase())
        )
        .sort((a, b) => a.price - b.price);
}, [products, search]);

Flow:

products
    +
search
    ↓
filter
    ↓
sort
    ↓
filteredAndSortedProducts

If only count changes:

count changes
    ↓
render
    ↓
products unchanged
search unchanged
    ↓
reuse previous result

12. Scenario 5 — Derived data

A very common use of useMemo is creating derived data.

Suppose:

const orders = [
    { id: 1, amount: 1000 },
    { id: 2, amount: 2000 },
    { id: 3, amount: 1500 }
];

You need the total:

const total = orders.reduce(
    (sum, order) => sum + order.amount,
    0
);

You could write:

const total = useMemo(() => {
    return orders.reduce(
        (sum, order) => sum + order.amount,
        0
    );
}, [orders]);

The data flow is:

orders
   ↓
reduce()
   ↓
total
   ↓
UI

If orders doesn't change, React can reuse the previous total.


13. Scenario 6 — Calculating statistics

For example:

const statistics = useMemo(() => {
    const total = orders.reduce(
        (sum, order) => sum + order.amount,
        0
    );

    const average = total / orders.length;

    const highest = Math.max(
        ...orders.map(order => order.amount)
    );

    return {
        total,
        average,
        highest
    };
}, [orders]);

You now have:

statistics.total
statistics.average
statistics.highest

This is useful for:

  • dashboards
  • reports
  • analytics
  • financial calculations
  • admin panels

14. Scenario 7 — Creating an object

This is where useMemo becomes slightly more interesting.

Suppose:

const options = {
    sortBy: "price",
    direction: "asc"
};

Every render creates a new object.

Even if the values are the same:

Render 1 → object A
Render 2 → object B
Render 3 → object C

The contents are the same, but the object references are different.

You can use:

const options = useMemo(() => {
    return {
        sortBy: "price",
        direction: "asc"
    };
}, []);

Now React can reuse the same object reference between renders.

This becomes particularly useful when the object is passed to another component or used as a dependency.


15. Why object references matter

Consider:

const options = {
    sortBy: "price"
};

Every render:

new object
     ↓
different reference

Even though:

options.sortBy === "price"

is still true.

But:

{} === {}

is:

false

because they are different objects.

This matters for React optimization.


16. Scenario 8 — Passing calculated data to a child component

Suppose:

function Parent() {
    const [count, setCount] = useState(0);

    const products = useMemo(() => {
        return [
            { id: 1, name: "Laptop" },
            { id: 2, name: "Mouse" }
        ];
    }, []);

    return (
        <>
            <button onClick={() => setCount(count + 1)}>
                {count}
            </button>

            <ProductList products={products} />
        </>
    );
}

The important point is that:

products

keeps the same reference between renders.

This becomes especially useful when the child is optimized with:

React.memo()

17. useMemo + React.memo

These two concepts are often used together.

Suppose:

const ProductList = React.memo(function ProductList({
    products
}: Props) {
    console.log("ProductList rendered");

    return (
        <div>
            {products.map(product => (
                <p key={product.id}>
                    {product.name}
                </p>
            ))}
        </div>
    );
});

Parent:

const products = useMemo(() => {
    return [
        { id: 1, name: "Laptop" },
        { id: 2, name: "Mouse" }
    ];
}, []);

Now:

Parent renders
      ↓
products reference remains same
      ↓
React.memo checks props
      ↓
props unchanged
      ↓
Child render can be skipped

So:

useMemo
   ↓
stabilizes value/reference

React.memo
   ↓
can skip child rendering

They solve different problems.


18. useMemo vs React.memo

Concept Purpose
useMemo Memoizes a calculated value
React.memo Memoizes a component's rendering
useCallback Memoizes a function reference

For example:

const value = useMemo(() => calculate(), [data]);

means:

Remember this value.

While:

const handleClick = useCallback(() => {
    // ...
}, []);

means:

Remember this function reference.

And:

const Child = React.memo(Component);

means:

Avoid rendering this child when its props haven't changed.


19. useMemo vs useCallback

This is a common interview question.

useMemo

const result = useMemo(() => {
    return calculate(a, b);
}, [a, b]);

It returns a value.

useCallback

const handleClick = useCallback(() => {
    console.log("Clicked");
}, []);

It returns a function.

Think:

useMemo
    ↓
remember result

useCallback
    ↓
remember function

Conceptually:

useCallback(fn, deps)

is closely related to:

useMemo(() => fn, deps)

20. Scenario 9 — Expensive transformation

Suppose your API returns:

const users = [
    {
        firstName: "John",
        lastName: "Smith"
    },
    {
        firstName: "David",
        lastName: "Brown"
    }
];

You need display names:

const displayUsers = useMemo(() => {
    return users.map(user => ({
        ...user,
        fullName: `${user.firstName} ${user.lastName}`
    }));
}, [users]);

Flow:

API data
   ↓
users
   ↓
map()
   ↓
displayUsers
   ↓
UI

Again, this is useful when the transformation is expensive or the data is large.


21. Scenario 10 — Dashboard calculations

Suppose an admin dashboard has:

10,000 transactions

You need:

Total Sales
Average Order
Highest Order
Completed Orders
Pending Orders
Failed Orders

You could calculate them together:

const dashboardStats = useMemo(() => {
    let totalSales = 0;
    let completed = 0;
    let pending = 0;
    let failed = 0;

    orders.forEach(order => {
        totalSales += order.amount;

        if (order.status === "Completed") {
            completed++;
        }

        if (order.status === "Pending") {
            pending++;
        }

        if (order.status === "Failed") {
            failed++;
        }
    });

    return {
        totalSales,
        completed,
        pending,
        failed
    };
}, [orders]);

This is a good use case because:

large data
    +
multiple calculations
    +
repeated renders

can make unnecessary calculations expensive.


22. Scenario 11 — Expensive filtering based on multiple inputs

Suppose you have:

const [search, setSearch] = useState("");
const [category, setCategory] = useState("All");
const [sortBy, setSortBy] = useState("price");

You can derive the visible products:

const visibleProducts = useMemo(() => {
    let result = products;

    if (search) {
        result = result.filter(product =>
            product.name
                .toLowerCase()
                .includes(search.toLowerCase())
        );
    }

    if (category !== "All") {
        result = result.filter(product =>
            product.category === category
        );
    }

    result = [...result].sort((a, b) => {
        if (sortBy === "price") {
            return a.price - b.price;
        }

        return a.name.localeCompare(b.name);
    });

    return result;
}, [products, search, category, sortBy]);

This is a very realistic use case for an e-commerce application.


23. Scenario 12 — Complex calculations in forms

Suppose a shopping cart has:

Products
Quantity
Discount
Tax
Shipping

You can derive the final amount:

const orderSummary = useMemo(() => {
    const subtotal = cart.reduce(
        (sum, item) => sum + item.price * item.quantity,
        0
    );

    const discountAmount = subtotal * discount / 100;

    const taxableAmount = subtotal - discountAmount;

    const taxAmount = taxableAmount * tax / 100;

    const finalAmount =
        taxableAmount + taxAmount + shipping;

    return {
        subtotal,
        discountAmount,
        taxAmount,
        shipping,
        finalAmount
    };
}, [cart, discount, tax, shipping]);

Now the UI can display:

Subtotal:        ₹10,000
Discount:        ₹1,000
Tax:             ₹1,620
Shipping:        ₹100
-----------------------
Total:           ₹10,720

24. Scenario 13 — useMemo with useState

This is extremely common.

const [products, setProducts] = useState<Product[]>([]);
const [search, setSearch] = useState("");
const [count, setCount] = useState(0);

const filteredProducts = useMemo(() => {
    return products.filter(product =>
        product.name
            .toLowerCase()
            .includes(search.toLowerCase())
    );
}, [products, search]);

Notice:

count

is not a dependency.

Therefore:

count changes
     ↓
component renders
     ↓
products unchanged
search unchanged
     ↓
filteredProducts reused

This is one of the main reasons developers use useMemo.


25. Scenario 14 — useMemo with useEffect

You need to be careful here.

Suppose:

const options = useMemo(() => ({
    category,
    sortBy
}), [category, sortBy]);

useEffect(() => {
    fetchProducts(options);
}, [options]);

Without useMemo:

const options = {
    category,
    sortBy
};

A new object is created on every render.

Therefore:

render
 ↓
new options object
 ↓
options reference changed
 ↓
useEffect runs

With useMemo:

category/sortBy unchanged
        ↓
same options reference
        ↓
useEffect dependency unchanged
        ↓
effect does not unnecessarily rerun

However, there is often an even simpler solution: create the object inside the effect when possible.

So don't automatically use useMemo just because an object appears in an effect dependency array.


26. Scenario 15 — useMemo with Context API

This is an advanced but important pattern.

Suppose:

const value = {
    user,
    login,
    logout
};

If this object is created during every render:

new object
     ↓
Provider value changes by reference
     ↓
Context consumers may re-render

You can stabilize the value:

const value = useMemo(() => ({
    user,
    login,
    logout
}), [user, login, logout]);

Then:

<AuthContext.Provider value={value}>
    {children}
</AuthContext.Provider>

But remember that login and logout themselves may need stable references, commonly using useCallback.

This can lead to:

useCallback
     ↓
stable functions

useMemo
     ↓
stable context value object

Context
     ↓
fewer unnecessary consumer updates

This is an optimization pattern, not something every Context provider automatically needs.


27. useMemo with useReducer

You can also derive data from reducer state.

const [state, dispatch] = useReducer(reducer, initialState);

const total = useMemo(() => {
    return state.items.reduce(
        (sum, item) => sum + item.price,
        0
    );
}, [state.items]);

Flow:

dispatch()
   ↓
reducer
   ↓
state changes
   ↓
useMemo checks state.items
   ↓
recalculate total if items changed

This is useful in complex applications such as:

  • shopping carts
  • workflow systems
  • admin dashboards
  • form builders

28. useMemo with API data

Imagine:

const [users, setUsers] = useState<User[]>([]);
const [search, setSearch] = useState("");

API returns:

10,000 users

You can derive the filtered users:

const filteredUsers = useMemo(() => {
    return users.filter(user =>
        user.name
            .toLowerCase()
            .includes(search.toLowerCase())
    );
}, [users, search]);

Important distinction:

useMemo does not cache the API response.

It caches the result of your calculation.

So:

API response
      ↓
users state
      ↓
useMemo
      ↓
filtered users

29. useMemo does NOT replace API caching

This is an important limitation.

Don't think:

useMemo(() => fetch("/api/products"), []);

is an API caching solution.

It isn't.

For server-state caching, tools such as:

  • TanStack Query
  • SWR
  • framework-specific data APIs

are more appropriate.

useMemo is primarily about memoizing calculations during component rendering.


30. useMemo and primitive values

Suppose:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

This is technically valid.

But ask:

Is this calculation expensive?

If:

price * quantity

is the calculation, then useMemo is probably unnecessary.

Simply use:

const total = price * quantity;

This is better because it is simpler.


31. When NOT to use useMemo

This is probably the most important practical lesson.

Do not use useMemo everywhere.

Bad example

const fullName = useMemo(() => {
    return firstName + " " + lastName;
}, [firstName, lastName]);

This calculation is extremely cheap.

Better:

const fullName = `${firstName} ${lastName}`;

Another bad example

const isAdult = useMemo(() => {
    return age >= 18;
}, [age]);

Better:

const isAdult = age >= 18;

Another example

const double = useMemo(() => {
    return count * 2;
}, [count]);

Better:

const double = count * 2;

32. Why not use useMemo everywhere?

Because useMemo itself has a cost.

React needs to:

store the memoized value
       ↓
store dependencies
       ↓
compare dependencies
       ↓
decide whether to reuse or recalculate

For a tiny calculation:

count * 2

the optimization may actually make the code more complicated without providing meaningful performance benefit.

So:

Don't optimize calculations that are already cheap.


33. useMemo is a performance optimization

This is an important React principle:

useMemo is an optimization.

Your application should ideally work correctly without relying on useMemo for correctness.

Bad design:

The application only works because useMemo is present.

Good design:

The application works correctly without useMemo.
useMemo improves performance.

Think of it as:

Correctness
    ↓
First priority

Performance optimization
    ↓
Second priority

34. Dependency array

The dependency array is critical.

Example:

const result = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

Here:

[price, quantity]

means:

Recalculate when price or quantity changes.


No dependency array

This:

useMemo(() => {
    return calculate();
});

is generally not useful as a memoization strategy because the calculation is eligible to run on every render.


Empty dependency array

useMemo(() => {
    return calculateSomething();
}, []);

This means the calculation has no reactive dependencies and React can reuse the value across renders.

But don't put [] simply to force a calculation to happen once if that calculation actually depends on changing values.


35. Wrong dependency example

Suppose:

const total = useMemo(() => {
    return price * quantity;
}, [price]);

This is incorrect because:

total depends on:
price
quantity

but only:

price

is listed.

If quantity changes:

quantity changes
      ↓
useMemo doesn't know
      ↓
old total may be reused

The correct version is:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

36. Dependency rule

A useful rule is:

Every reactive value used inside the calculation should generally be included in the dependency array.

For example:

const result = useMemo(() => {
    return price * quantity * taxRate;
}, [price, quantity, taxRate]);

because the calculation depends on all three.


37. Objects and dependency arrays

Consider:

const user = {
    name: "John",
    age: 30
};

Then:

const result = useMemo(() => {
    return user.name;
}, [user]);

If user is recreated on every render:

render 1 → user object A
render 2 → user object B
render 3 → user object C

React sees:

user changed

because the reference changed.

Therefore the memoization may not provide much benefit.

This is why understanding reference equality is important when using useMemo.


38. Reference equality

For primitive values:

10 === 10

is:

true

For objects:

{} === {}

is:

false

For arrays:

[] === []

is:

false

For functions:

(() => {}) === (() => {})

is:

false

Each creates a new reference.

This is why React optimization techniques often involve stable references.


39. useMemo with arrays

Suppose:

const items = useMemo(() => {
    return [1, 2, 3, 4];
}, []);

The array reference remains stable across renders.

This can be useful when passing it to:

React.memo

or when it is used as a dependency elsewhere.

But don't do this merely because you have an array.

Use it when reference stability provides an actual benefit.


40. useMemo with objects

Same concept:

const settings = useMemo(() => ({
    theme: "dark",
    language: "en"
}), []);

The object reference is preserved.

Useful when:

object passed to memoized child
OR
object used as dependency
OR
object creation/calculation is expensive

41. useMemo with functions

Don't use useMemo to memoize functions.

Instead:

const handleClick = useCallback(() => {
    console.log("Clicked");
}, []);

Use:

useMemo → values
useCallback → functions

42. Important: useMemo is not the same as useRef

Since you recently looked at useRef, this distinction is important.

useMemo

const value = useMemo(() => calculate(), [data]);

Purpose:

Remember a calculated value.

useRef

const valueRef = useRef(initialValue);

Purpose:

Store a value that persists between renders without causing a render when changed.

Think:

useMemo
   ↓
memoized calculation

useRef
   ↓
persistent mutable storage

They are not interchangeable.


43. useMemo vs useRef

Feature useMemo useRef
Main purpose Cache calculation Store persistent value
Re-render when changed? N/A No
Calculates value? Yes No
Dependency array Yes No
Common use Expensive calculation DOM/value storage
Can mutate .current? No Yes
Used for DOM element? No Yes

44. useMemo and rendering

Suppose:

function App() {
    const [count, setCount] = useState(0);

    const result = useMemo(() => {
        console.log("Calculating...");
        return 1000;
    }, []);

    console.log("App rendered");

    return (
        <>
            <p>{count}</p>

            <button onClick={() => setCount(count + 1)}>
                Increase
            </button>
        </>
    );
}

Click the button several times.

You may see:

App rendered
Calculating...

App rendered
App rendered
App rendered

The component renders every time.

But the memoized calculation isn't repeated.

This is the correct mental model.


45. useMemo and Strict Mode

During development, React Strict Mode can cause certain functions to execute more than once as part of development checks.

Therefore, don't assume:

console.log()

inside useMemo

will always execute exactly once during development.

This is especially important when debugging.

Your calculation should also be pure.

Avoid doing side effects inside useMemo.

Bad:

const result = useMemo(() => {
    fetch("/api/products");

    return calculate();
}, []);

useMemo should not be used for side effects.

Use:

useEffect(...)

for side effects.


46. useMemo vs useEffect

This is another important interview comparison.

useMemo

Used to calculate a value:

const total = useMemo(() => {
    return calculateTotal(items);
}, [items]);

useEffect

Used for side effects:

useEffect(() => {
    fetchProducts();
}, []);

Think:

useMemo
→ "I need to calculate something."

useEffect
→ "I need to do something outside rendering."

Examples of side effects:

  • API calls
  • subscriptions
  • timers
  • browser APIs
  • DOM-related external operations

47. useMemo and expensive child rendering

Suppose:

const filteredProducts = useMemo(() => {
    return filterProducts(products, search);
}, [products, search]);

and:

<ProductList products={filteredProducts} />

If ProductList is:

const ProductList = React.memo(...);

then stable filteredProducts references can help React determine whether the child needs to render.

The optimization chain becomes:

useMemo
   ↓
stable derived value
   ↓
React.memo
   ↓
child can skip rendering

This is a common performance pattern.


48. useMemo + useCallback + React.memo

You may see all three together:

const filteredProducts = useMemo(() => {
    return filterProducts(products, search);
}, [products, search]);

const handleSelect = useCallback((id: number) => {
    setSelectedId(id);
}, []);

return (
    <ProductList
        products={filteredProducts}
        onSelect={handleSelect}
    />
);

Child:

const ProductList = React.memo(function ProductList(props) {
    // ...
});

Each has a different responsibility:

useMemo
    ↓
memoize calculated value

useCallback
    ↓
memoize function reference

React.memo
    ↓
memoize component rendering

49. TypeScript example

Suppose:

interface Product {
    id: number;
    name: string;
    price: number;
    category: string;
}

State:

const [products, setProducts] = useState<Product[]>([]);
const [search, setSearch] = useState("");

Memoized filtering:

const filteredProducts = useMemo<Product[]>(() => {
    return products.filter(product =>
        product.name
            .toLowerCase()
            .includes(search.toLowerCase())
    );
}, [products, search]);

Usually, TypeScript can infer the type, so this is also sufficient:

const filteredProducts = useMemo(() => {
    return products.filter(product =>
        product.name
            .toLowerCase()
            .includes(search.toLowerCase())
    );
}, [products, search]);

The result is automatically inferred as:

Product[]

50. TypeScript example — derived statistics

interface Order {
    id: number;
    amount: number;
    status: "Completed" | "Pending" | "Failed";
}

interface OrderStats {
    total: number;
    completed: number;
    pending: number;
    failed: number;
}

Then:

const stats = useMemo<OrderStats>(() => {
    let total = 0;
    let completed = 0;
    let pending = 0;
    let failed = 0;

    orders.forEach(order => {
        total += order.amount;

        if (order.status === "Completed") completed++;
        if (order.status === "Pending") pending++;
        if (order.status === "Failed") failed++;
    });

    return {
        total,
        completed,
        pending,
        failed
    };
}, [orders]);

51. Advanced pattern — Memoizing a transformation pipeline

Suppose:

const result = useMemo(() => {
    return products
        .filter(product => product.category === category)
        .filter(product =>
            product.name.toLowerCase().includes(search.toLowerCase())
        )
        .sort((a, b) => a.price - b.price)
        .map(product => ({
            ...product,
            displayPrice: `₹${product.price}`
        }));
}, [products, category, search]);

The entire pipeline is memoized:

products
   ↓
category filter
   ↓
search filter
   ↓
sort
   ↓
map
   ↓
result

It doesn't need to be repeated when unrelated state changes.


52. Advanced pattern — Memoizing grouped data

Suppose you want products grouped by category.

const productsByCategory = useMemo(() => {
    return products.reduce<Record<string, Product[]>>(
        (groups, product) => {
            if (!groups[product.category]) {
                groups[product.category] = [];
            }

            groups[product.category].push(product);

            return groups;
        },
        {}
    );
}, [products]);

Result:

Electronics
    Laptop
    Mouse
    Keyboard

Furniture
    Chair
    Table

This is useful for:

  • grouped dropdowns
  • category pages
  • reports
  • dashboards
  • navigation menus

53. Advanced pattern — Memoizing expensive tree data

For hierarchical data:

Category
   ↓
Subcategory
   ↓
Product

You might need to transform a flat API response into a tree.

const tree = useMemo(() => {
    return buildProductTree(products);
}, [products]);

If buildProductTree() is expensive, this is a good candidate for memoization.


54. Advanced pattern — Derived permissions

Suppose your application has:

user
permissions

You can derive available actions:

const availableActions = useMemo(() => {
    return {
        canCreate: permissions.includes("CREATE"),
        canEdit: permissions.includes("EDIT"),
        canDelete: permissions.includes("DELETE")
    };
}, [permissions]);

Then:

{availableActions.canCreate && (
    <button>Create</button>
)}

This can make permission-based UI logic easier to organize.

For a tiny permissions list, however, useMemo may not be necessary.


55. Advanced pattern — Memoizing expensive search

For client-side search over large datasets:

const searchResults = useMemo(() => {
    if (!search.trim()) {
        return products;
    }

    const searchText = search.toLowerCase();

    return products.filter(product => {
        return (
            product.name.toLowerCase().includes(searchText) ||
            product.category.toLowerCase().includes(searchText)
        );
    });
}, [products, search]);

This is particularly useful when:

large dataset
+
expensive filtering
+
frequent renders

56. Important: useMemo does not make every calculation faster

This is a common misunderstanding.

Suppose:

const result = useMemo(() => {
    return a + b;
}, [a, b]);

You have introduced:

dependency checking
+
memoization overhead
+
more code

to avoid:

a + b

which is already extremely cheap.

Therefore, the application may not become faster in any meaningful way.

The goal is not:

"Use useMemo everywhere."

The goal is:

Use useMemo where repeated computation is actually expensive or where stable references provide a meaningful optimization.


57. How to decide whether to use useMemo

Ask these questions:

Question 1

Is the calculation expensive?

Large filtering?
Large sorting?
Complex transformation?
Large aggregation?
Complex tree construction?

If yes → consider useMemo.

Question 2

Does the calculation happen frequently?

If the component rarely renders, optimization may not matter.

Question 3

Does the calculated value need a stable reference?

For example:

object
array
derived data

passed to a memoized child.

If yes → useMemo may help.

Question 4

Is the calculation tiny?

const total = price * quantity;

If yes → don't use useMemo.


58. A practical decision example

Suppose:

const fullName = `${firstName} ${lastName}`;

Use:

const fullName = `${firstName} ${lastName}`;

Not:

const fullName = useMemo(
    () => `${firstName} ${lastName}`,
    [firstName, lastName]
);

But suppose:

const visibleProducts = products
    .filter(...)
    .sort(...)
    .map(...)

and:

products = 50,000 records

Then:

const visibleProducts = useMemo(() => {
    return products
        .filter(...)
        .sort(...)
        .map(...);
}, [products, search, category]);

may be worthwhile.


59. Common mistake — Using useMemo for side effects

Wrong:

useMemo(() => {
    localStorage.setItem("user", JSON.stringify(user));
}, [user]);

Don't use useMemo for this.

Use an effect:

useEffect(() => {
    localStorage.setItem("user", JSON.stringify(user));
}, [user]);

Remember:

useMemo → calculate a value

useEffect → perform a side effect

60. Common mistake — Mutating state inside useMemo

Avoid:

const sortedProducts = useMemo(() => {
    products.sort((a, b) => a.price - b.price);

    return products;
}, [products]);

sort() modifies the array.

Prefer:

const sortedProducts = useMemo(() => {
    return [...products].sort(
        (a, b) => a.price - b.price
    );
}, [products]);

This maintains immutability.


61. Common mistake — Missing dependencies

Bad:

const total = useMemo(() => {
    return price * quantity;
}, [price]);

Correct:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

Missing dependencies can produce stale values.


62. Common mistake — Adding unnecessary dependencies

Suppose:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity, count]);

But count isn't used.

Then:

count changes
    ↓
useMemo recalculates

even though the result doesn't depend on count.

Better:

[price, quantity]

Dependencies should represent what the calculation actually depends on.


63. Common mistake — Expecting useMemo to prevent rendering

Wrong mental model:

useMemo prevents component rendering.

Correct:

useMemo prevents unnecessary recalculation.

The component can still render.


64. Common mistake — Using useMemo everywhere

Avoid code like:

const a = useMemo(() => x + y, [x, y]);

const b = useMemo(() => name.toUpperCase(), [name]);

const c = useMemo(() => age >= 18, [age]);

const d = useMemo(() => price * quantity, [price, quantity]);

Most of these calculations are trivial.

This makes the code harder to read.


65. Common mistake — Thinking useMemo is permanent storage

Don't think:

useMemo = permanent cache

It isn't a general-purpose persistent cache.

It's a React rendering optimization.

If you need persistent storage, consider:

localStorage
sessionStorage
database
server cache
React state
useRef
query cache

depending on the requirement.


66. Common mistake — Using useMemo instead of better architecture

If filtering 1 million records in the browser is slow, adding useMemo may not solve the fundamental problem.

You may need:

server-side filtering
pagination
virtualization
database queries
search indexing

For example:

1,000,000 records
       ↓
Browser
       ↓
useMemo

may still be a poor architecture.

Instead:

Search term
    ↓
API
    ↓
Database
    ↓
Filtered records
    ↓
Browser

67. useMemo and server-side filtering

Suppose your database contains:

500,000 products

Don't necessarily download all 500,000 products and then use:

useMemo(() => products.filter(...))

Instead, consider:

Search "Laptop"
       ↓
API
       ↓
Database WHERE Name LIKE '%Laptop%'
       ↓
Return matching records

useMemo is useful for client-side computation, not a replacement for backend optimization.


68. useMemo and pagination

Suppose:

10,000 products

If pagination already gives you:

20 products per page

then:

products.filter(...)

may be cheap.

In that situation, useMemo may not provide much benefit.

Always consider the actual size and cost of the operation.


69. useMemo and virtualization

For very large lists, consider list virtualization.

Instead of rendering:

10,000 DOM elements

virtualization might render only:

20–50 visible elements

Examples include virtualization libraries such as TanStack Virtual.

So:

useMemo

optimizes calculations.

While:

virtualization

optimizes rendering large lists.

They solve different problems.


70. useMemo and React Compiler

Modern React also has compiler-based optimization capabilities.

The important practical lesson is:

Don't automatically add manual memoization everywhere.

When using a modern React setup with the React Compiler enabled, some manual memoization can become less necessary because the compiler can optimize certain patterns automatically.

However, understanding useMemo remains important because:

  • existing applications use it
  • interviews ask about it
  • you need to understand dependency behavior
  • you may encounter manual memoization in production code
  • some optimization scenarios still require explicit reasoning

71. A complete real-world example

Let's build a small product search component.

import { useMemo, useState } from "react";

interface Product {
    id: number;
    name: string;
    category: string;
    price: number;
}

const products: Product[] = [
    {
        id: 1,
        name: "Laptop",
        category: "Electronics",
        price: 60000
    },
    {
        id: 2,
        name: "Mouse",
        category: "Electronics",
        price: 1000
    },
    {
        id: 3,
        name: "Office Chair",
        category: "Furniture",
        price: 8000
    },
    {
        id: 4,
        name: "Keyboard",
        category: "Electronics",
        price: 2500
    }
];

function ProductSearch() {
    const [search, setSearch] = useState("");
    const [category, setCategory] = useState("All");
    const [count, setCount] = useState(0);

    const filteredProducts = useMemo(() => {
        return products
            .filter(product => {
                const matchesSearch =
                    product.name
                        .toLowerCase()
                        .includes(search.toLowerCase());

                const matchesCategory =
                    category === "All" ||
                    product.category === category;

                return matchesSearch && matchesCategory;
            })
            .sort((a, b) => a.price - b.price);
    }, [search, category]);

    return (
        <div>
            <h2>Products</h2>

            <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search product"
            />

            <select
                value={category}
                onChange={e => setCategory(e.target.value)}
            >
                <option value="All">All</option>
                <option value="Electronics">
                    Electronics
                </option>
                <option value="Furniture">
                    Furniture
                </option>
            </select>

            <button onClick={() => setCount(count + 1)}>
                Count: {count}
            </button>

            <hr />

            {filteredProducts.map(product => (
                <div key={product.id}>
                    <h3>{product.name}</h3>
                    <p>{product.category}</p>
                    <p>₹{product.price}</p>
                </div>
            ))}
        </div>
    );
}

What is happening?

There are three pieces of state:

search
category
count

But filteredProducts depends only on:

search
category

Therefore:

search changes
     ↓
recalculate products
category changes
     ↓
recalculate products

But:

count changes
     ↓
component renders
     ↓
search unchanged
category unchanged
     ↓
reuse filteredProducts

This is a good example of the purpose of useMemo.


72. Data flow in the example

                 products
                    │
                    ▼
        ┌─────────────────────┐
        │      useMemo        │
        │                     │
search ─► filter              │
        │                     │
category► filter              │
        │                     │
        │ sort                │
        └──────────┬──────────┘
                   │
                   ▼
          filteredProducts
                   │
                   ▼
                  UI

And:

count changes
     ↓
Parent renders
     ↓
useMemo checks:
search? unchanged
category? unchanged
     ↓
reuse filteredProducts

73. useMemo mental model

The easiest way to remember it is:

const result = useMemo(
    () => calculateSomething(),
    [dependencies]
);

Read this as:

"React, remember the result of this calculation. If these dependencies haven't changed, give me the previous result."

For example:

const total = useMemo(
    () => price * quantity,
    [price, quantity]
);

Read it as:

"Remember price * quantity. Recalculate it when price or quantity changes."


74. useMemo vs normal calculation

Normal calculation

const result = expensiveCalculation(data);

Every render:

render
 ↓
calculate
 ↓
render
 ↓
calculate
 ↓
render
 ↓
calculate

useMemo

const result = useMemo(
    () => expensiveCalculation(data),
    [data]
);

Behavior:

First render
 ↓
calculate
 ↓
remember result

Next render
 ↓
data unchanged
 ↓
reuse result

Next render
 ↓
data unchanged
 ↓
reuse result

data changes
 ↓
calculate again
 ↓
remember new result

75. Important rule: optimize only after identifying a problem

A good development approach is:

Build application
      ↓
Measure performance
      ↓
Find expensive calculation
      ↓
Use useMemo if appropriate
      ↓
Measure again

Don't start with:

Everything must use useMemo.

Instead:

Problem → Measure → Optimize

76. Interview-focused questions

What is useMemo?

useMemo is a React Hook that memoizes the result of a calculation and reuses that result until its dependencies change.

Does useMemo prevent component re-rendering?

No. The component can still re-render. useMemo mainly prevents unnecessary recalculation of a memoized value.

When should you use useMemo?

Use it for expensive calculations or when maintaining a stable object/array reference provides a meaningful performance benefit.

When should you not use useMemo?

Don't use it for simple calculations such as:

const total = price * quantity;

because the memoization overhead and complexity are unnecessary.

What does the dependency array do?

It tells React when the memoized calculation needs to be recalculated.

useMemo(() => calculate(a, b), [a, b]);

The calculation is recomputed when a or b changes.

What does useMemo return?

It returns the memoized value, not a function.

useMemo vs useCallback?

useMemo
→ memoizes a value

useCallback
→ memoizes a function reference

useMemo vs React.memo?

useMemo
→ memoizes a calculated value

React.memo
→ memoizes component rendering based on props

Can useMemo be used for API calls?

No. API calls are side effects. Use useEffect or an appropriate data-fetching library.

Can useMemo guarantee that React will always keep the cached value?

You should treat it as a performance optimization, not as permanent storage or a general-purpose cache.


77. The three React memoization concepts

Remember these three:

                Memoization
                    │
       ┌────────────┼────────────┐
       │            │            │
       ▼            ▼            ▼
   useMemo      useCallback   React.memo
       │            │            │
       ▼            ▼            ▼
    Value         Function     Component

useMemo

const result = useMemo(() => calculate(), [data]);

Remember a value.

useCallback

const fn = useCallback(() => {
    // ...
}, [data]);

Remember a function reference.

React.memo

const Child = React.memo(ChildComponent);

Avoid unnecessary child rendering when props are unchanged.


78. Most important points to remember

  1. useMemo memoizes a calculated value.
  2. It is mainly a performance optimization.
  3. It does not prevent the parent component from rendering.
  4. The calculation runs again when its dependencies change.
  5. Don't use it for every calculation.
  6. Simple calculations usually don't need it.
  7. It is useful for expensive filtering, sorting, aggregation, and transformations.
  8. It can also help maintain stable object/array references.
  9. useMemo returns a value.
  10. useCallback returns a function.
  11. React.memo optimizes component rendering.
  12. Don't use useMemo for side effects.
  13. Don't mutate arrays/objects inside memoized calculations.
  14. Keep dependency arrays correct.
  15. Don't treat useMemo as permanent storage.
  16. For huge datasets, consider better architecture such as server-side filtering or virtualization.
  17. Measure performance before adding memoization.
  18. Modern React tooling may reduce the need for manual memoization in some cases, but understanding useMemo remains important.

79. The simplest way to remember useMemo

Imagine you have a calculator:

Input:
100 products

Calculation:
filter + sort + transform

Result:
20 products

Without useMemo:

Every render
     ↓
Do the calculation again

With useMemo:

First render
     ↓
Calculate
     ↓
Remember result

Next render
     ↓
Did input change?
     ↓
NO
     ↓
Use previous result

So the core idea is simply:

useMemo remembers the result of an expensive calculation and recalculates it only when its dependencies change.

And the most important practical rule is:

Don't use useMemo because you can. Use it when there is a meaningful performance reason.

 

useMemo vs useEffect

The easiest way to understand the difference is:

useMemo calculates and returns a value.
useEffect performs a side effect after rendering.

They may look similar because both have a dependency array, but they solve completely different problems.

Basic difference

useMemo useEffect
Used to calculate a value Used to perform a side effect
Runs during rendering Runs after rendering
Returns a memoized value Does not return a value for rendering
Optimizes expensive calculations Synchronizes with external systems
Used for derived data Used for API calls, timers, subscriptions, etc.
Dependency changes → calculation runs again Dependency changes → effect runs again

1. useMemo — calculate a value

Suppose you have:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

You are telling React:

"Calculate price * quantity and remember the result. Recalculate it when price or quantity changes."

Flow:

price + quantity
       ↓
    useMemo
       ↓
   calculate
       ↓
     total
       ↓
      UI

For example:

price = 100
quantity = 5

      ↓

useMemo

      ↓

total = 500

This is calculation, not a side effect.


2. useEffect — perform an action

Suppose you want to call an API:

useEffect(() => {
    fetch("/api/products");
}, []);

You are telling React:

"After the component renders, perform this operation."

Flow:

Component renders
       ↓
React updates UI
       ↓
useEffect runs
       ↓
API call

An API call is a side effect.

Other examples of side effects:

  • API calls
  • timers
  • subscriptions
  • WebSocket connections
  • browser APIs
  • updating document.title
  • interacting with external libraries
  • adding/removing event listeners

3. The biggest difference: calculation vs action

Think about these two requirements.

Requirement A

Calculate the total price.

Use:

const total = useMemo(() => {
    return price * quantity;
}, [price, quantity]);

Requirement B

Save the total price to an API whenever it changes.

Use:

useEffect(() => {
    saveOrderTotal(total);
}, [total]);

So:

Calculate something
      ↓
   useMemo

Do something
      ↓
   useEffect

4. Very simple example

function Cart() {
    const [price, setPrice] = useState(100);
    const [quantity, setQuantity] = useState(2);

    const total = useMemo(() => {
        return price * quantity;
    }, [price, quantity]);

    useEffect(() => {
        console.log("Total changed:", total);
    }, [total]);

    return (
        <div>
            <p>Total: ₹{total}</p>
        </div>
    );
}

The flow is:

price / quantity change
          ↓
       Render
          ↓
      useMemo
          ↓
    Calculate total
          ↓
        UI
          ↓
      useEffect
          ↓
   Log total / side effect

Notice the order.

useMemo helps produce the value during rendering.

useEffect runs after rendering.


5. useMemo does not replace useEffect

Consider this:

const products = useMemo(() => {
    return fetch("/api/products");
}, []);

This is wrong.

Why?

Because fetch() is an external operation/side effect.

You should use:

useEffect(() => {
    fetch("/api/products");
}, []);

So:

❌ useMemo → API call

✅ useEffect → API call

6. useEffect does not replace useMemo

Now consider:

useEffect(() => {
    const total = price * quantity;
}, [price, quantity]);

This is also not the correct approach if your purpose is simply to calculate a value for rendering.

You cannot directly use that total in your JSX.

Instead:

const total = price * quantity;

or, if the calculation is genuinely expensive:

const total = useMemo(() => {
    return expensiveCalculation(price, quantity);
}, [price, quantity]);

So:

Need a value?
     ↓
useMemo / normal calculation

Need to perform an external action?
     ↓
useEffect

7. Example: Search/filter

Suppose you have 10,000 products.

You want to filter them based on a search box.

const filteredProducts = useMemo(() => {
    return products.filter(product =>
        product.name
            .toLowerCase()
            .includes(search.toLowerCase())
    );
}, [products, search]);

Why useMemo?

Because:

products + search
       ↓
filter calculation
       ↓
filteredProducts

You are calculating data.


What if you use useEffect?

You might write:

const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);

useEffect(() => {
    const result = products.filter(product =>
        product.name
            .toLowerCase()
            .includes(search.toLowerCase())
    );

    setFilteredProducts(result);
}, [products, search]);

This can work, but it introduces an unnecessary state/effect cycle.

The flow becomes:

search changes
     ↓
render
     ↓
useEffect
     ↓
filter products
     ↓
setFilteredProducts()
     ↓
another render

That's unnecessary for simple derived data.

Prefer:

const filteredProducts = useMemo(() => {
    return products.filter(...);
}, [products, search]);

8. Derived data is an important clue

If you have:

Existing data
     ↓
Calculation
     ↓
New value

you often want a normal calculation or useMemo.

Examples:

const fullName = `${firstName} ${lastName}`;
const total = price * quantity;
const filteredProducts = useMemo(...);
const totalOrders = orders.length;

These are derived values.

They don't need useEffect.


9. External system is an important clue

If you need to interact with something outside React, think useEffect.

Examples:

useEffect(() => {
    fetchProducts();
}, []);
useEffect(() => {
    document.title = `Cart (${count})`;
}, [count]);
useEffect(() => {
    const timer = setInterval(() => {
        console.log("Running...");
    }, 1000);

    return () => clearInterval(timer);
}, []);
useEffect(() => {
    window.addEventListener("resize", handleResize);

    return () => {
        window.removeEventListener("resize", handleResize);
    };
}, []);

These are side effects.


10. Dependency arrays look similar, but mean different things

useMemo

const result = useMemo(() => {
    return calculate(a, b);
}, [a, b]);

Means:

Recalculate the value when a or b changes.

useEffect

useEffect(() => {
    saveData(a, b);
}, [a, b]);

Means:

Run the side effect when a or b changes.

The dependency arrays have a similar purpose, but the hooks themselves do different jobs.


11. useMemo runs during rendering

Consider:

const total = useMemo(() => {
    console.log("Calculating...");
    return price * quantity;
}, [price, quantity]);

Conceptually:

React starts rendering
        ↓
useMemo calculation
        ↓
React gets total
        ↓
React renders JSX

So useMemo is part of producing the rendered result.


12. useEffect runs after rendering

Consider:

useEffect(() => {
    console.log("Effect running");
}, []);

Conceptually:

React renders component
        ↓
React updates DOM/UI
        ↓
Effect runs

This distinction is important.

useMemo
   ↓
during rendering

useEffect
   ↓
after rendering

13. A practical API example

Suppose you want to:

  1. Fetch products.
  2. Filter products.
  3. Display filtered products.

Use both hooks for different jobs.

function Products() {
    const [products, setProducts] = useState<Product[]>([]);
    const [search, setSearch] = useState("");

    // Side effect
    useEffect(() => {
        fetch("/api/products")
            .then(response => response.json())
            .then(data => setProducts(data));
    }, []);

    // Derived calculation
    const filteredProducts = useMemo(() => {
        return products.filter(product =>
            product.name
                .toLowerCase()
                .includes(search.toLowerCase())
        );
    }, [products, search]);

    return (
        <>
            <input
                value={search}
                onChange={e => setSearch(e.target.value)}
            />

            {filteredProducts.map(product => (
                <p key={product.id}>
                    {product.name}
                </p>
            ))}
        </>
    );
}

Here:

             API
              ↓
          useEffect
              ↓
        setProducts()
              ↓
           products
              ↓
          useMemo
              ↓
      filteredProducts
              ↓
              UI

This is a very important real-world pattern.


14. useEffect + useMemo can work together

They are not competing hooks.

They can work together:

useEffect(() => {
    fetchProducts();
}, []);

const filteredProducts = useMemo(() => {
    return products.filter(...);
}, [products, search]);

Their responsibilities are different:

useEffect
    ↓
Get/update external data

useMemo
    ↓
Process/derive that data

15. Another real-world example — Shopping cart

Suppose you have:

const [cart, setCart] = useState<CartItem[]>([]);

Calculate total:

const total = useMemo(() => {
    return cart.reduce(
        (sum, item) =>
            sum + item.price * item.quantity,
        0
    );
}, [cart]);

Then save the cart to local storage:

useEffect(() => {
    localStorage.setItem(
        "cart",
        JSON.stringify(cart)
    );
}, [cart]);

Now each hook has a clear job:

cart
 ↓
 ├── useMemo → calculate total
 │
 └── useEffect → save cart to localStorage

This is an excellent way to remember the difference.


16. useMemo vs useEffect vs useState

These three are often confused.

Hook Main purpose
useState Store data that changes
useMemo Calculate/cache derived data
useEffect Perform side effects

Example:

const [products, setProducts] = useState<Product[]>([]);

Store products.

const filteredProducts = useMemo(() => {
    return products.filter(...);
}, [products, search]);

Calculate filtered products.

useEffect(() => {
    fetchProducts();
}, []);

Fetch products.

So:

useState
   ↓
Store

useMemo
   ↓
Calculate

useEffect
   ↓
Act / synchronize

17. Common interview trap

Question:

"I have a filtered list. Should I use useEffect to filter it?"

Usually, no.

If filtering is just derived from existing state/props:

const filteredProducts = useMemo(() => {
    return products.filter(...);
}, [products, search]);

or simply:

const filteredProducts = products.filter(...);

if the calculation is cheap.

You generally don't need:

useEffect(() => {
    setFilteredProducts(...);
}, [products, search]);

because that creates additional state and an additional render cycle.


18. Another interview trap

Question:

"I need to call an API whenever userId changes. Should I use useMemo?"

No.

Use:

useEffect(() => {
    fetchUser(userId);
}, [userId]);

Because API communication is a side effect.


19. Another interview trap

Question:

"I need to calculate the total whenever items change. Should I use useEffect?"

Usually no.

If the total is derived data:

const total = useMemo(() => {
    return items.reduce(
        (sum, item) => sum + item.price,
        0
    );
}, [items]);

Or if the calculation is cheap:

const total = items.reduce(
    (sum, item) => sum + item.price,
    0
);

You don't need an effect just to calculate derived data.


20. The easiest decision rule

When you are unsure, ask:

"Am I calculating something?"

YES
 ↓
normal calculation
or
useMemo if expensive

"Am I doing something outside React?"

YES
 ↓
useEffect

Examples:

Filter array             → useMemo / normal calculation
Sort array               → useMemo / normal calculation
Calculate total          → useMemo / normal calculation
Calculate average        → useMemo / normal calculation

API call                 → useEffect
Timer                    → useEffect
WebSocket                → useEffect
Event listener           → useEffect
localStorage sync        → useEffect
document.title           → useEffect
External library sync    → useEffect

21. One-line interview answer

useMemo memoizes the result of a calculation and recomputes it when dependencies change, while useEffect runs side effects after rendering when its dependencies change.

Or remember:

useMemo
→ "What value should I calculate?"

useEffect
→ "What action should I perform after rendering?"

That distinction will help you decide between them in most real-world React situations.

← Back to Articles