DEV Community

Cover image for Simplifying React Hooks: useMemo 💯
Ali Samir
Ali Samir

Posted on

2

Simplifying React Hooks: useMemo 💯

Introduction

React provides several hooks that help optimize performance and enhance functionality. One of these hooks is useMemo, essential for memoizing computationally expensive calculations and avoiding unnecessary re-renders.

In this article, we will explore useMemo in-depth, understand its use cases, and implement it using TypeScript.


What is useMemo? 🤔

useMemo is a React Hook that memoizes the result of an expensive computation. It helps prevent recalculating values unless the dependencies change.

Syntax:

const memoizedValue = useMemo<T>(() => computeExpensiveValue(a, b), [a, b]);
Enter fullscreen mode Exit fullscreen mode
  • The first argument is a function that returns the computed value.

  • The second argument is the dependency array; when any value in this array changes, the function recomputes the memoized value.


Why Use useMemo? ✅

🔹 Avoid Unnecessary Computations

If your component performs expensive calculations, useMemo ensures that the computation only runs when necessary.

🔹 Optimize Performance

In large-scale applications, performance bottlenecks can arise from re-executing functions that return the same result. useMemo helps optimize such scenarios.

🔹 Prevent Unnecessary Re-Renders

If a component passes computed values as props, useMemo ensures these values do not change unless necessary, reducing re-renders.


Using useMemo

Example 1: Basic Usage

import React, { useState, useMemo } from "react";

const ExpensiveComponent: React.FC = () => {
  const [count, setCount] = useState<number>(0);
  const [input, setInput] = useState<string>("");

  const expensiveCalculation = (num: number): number => {
    console.log("Calculating...");
    return num * 2;
  };

  const memoizedResult = useMemo(() => expensiveCalculation(count), [count]);

  return (
    <div>
      <h2>useMemo Example</h2>
      <p>Memoized Result: {memoizedResult}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Type something..."
      />
    </div>
  );
};

export default ExpensiveComponent;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The expensiveCalculation function is memoized, preventing unnecessary recalculations when only input changes.

  • The function only runs when count updates.


Example 2: Optimizing an Expensive List Computation

interface Item {
  id: number;
  name: string;
}

const ListComponent: React.FC<{ items: Item[] }> = ({ items }) => {
  const sortedItems = useMemo(() => {
    console.log("Sorting items...");
    return [...items].sort((a, b) => a.name.localeCompare(b.name));
  }, [items]);

  return (
    <ul>
      {sortedItems.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Sorting an array is computationally expensive.

  • useMemo ensures sorting happens only when items change, improving efficiency.


Common Mistakes and Best Practices 💯

✅ Use useMemo only when needed - Overusing useMemo can lead to unnecessary complexity.

✅ Ensure dependencies are correct - Incorrect dependencies may lead to stale or unnecessary recalculations.

✅ Avoid memoizing non-expensive operations - If a function is cheap, useMemo may introduce overhead.

✅ Use it for the derived state, not direct state updates - useMemo should not replace useState or useEffect.


Conclusion 🔥

useMemo is a powerful hook for optimizing performance in React applications, particularly when dealing with expensive computations. Using it wisely with TypeScript helps prevent unnecessary renders and boosts efficiency.

Developers can build highly optimized applications by understanding their use cases and applying best practices.


🌐 Connect With Me On:

📍 LinkedIn
📍 X (Twitter)
📍 Telegram
📍 Instagram

Happy Coding!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay