Improve JavaScript Performance with Memoization Techniques

Mitesh KukdejaMitesh Kukdeja
3 min read

Have you ever called the same function with the same inputs multiple times and wished it could just remember the result? That’s exactly what memoization helps with.

Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.


⚡ Why Use Memoization?

  • ⏱ Reduces redundant computations
  • 🧮 Especially useful for pure functions and heavy calculations
  • 🧠 Improves performance in recursive algorithms, UI rendering, and more

📦 Real-World Analogy

Think of a student who solves a complex math problem and writes the answer in a notebook. Next time they encounter the same problem, they look it up in the notebook instead of solving it again.


🔁 Basic Memoization Example

function slowSquare(n) {
  console.log("Calculating square...");
  return n * n;
}

function memoize(fn) {
  const cache = new Map();
  return function (arg) {
    if (cache.has(arg)) {
      console.log("Fetching from cache...");
      return cache.get(arg);
    }
    const result = fn(arg);
    cache.set(arg, result);
    return result;
  };
}

const fastSquare = memoize(slowSquare);

console.log(fastSquare(4)); // Calculating square...
console.log(fastSquare(4)); // Fetching from cache...

🔄 Recursive Example: Fibonacci

Fibonacci numbers are a classic use case for memoization:

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = args.toString();
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

const fibonacci = memoize(function fib(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
});

console.log(fibonacci(30)); // Much faster with memoization

⚛️ Memoization in React: useMemo and useCallback

React offers built-in hooks like useMemo() and useCallback() to help avoid unnecessary re-renders and recomputations.


📌 useMemo

useMemo memoizes the result of a function value so it only recalculates when its dependencies change.

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

function ExpensiveComponent({ number }) {
  const squared = useMemo(() => {
    console.log("Squaring...");
    return number * number;
  }, [number]);

  return <p>Squared: {squared}</p>;
}

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

  return (
    <div>
      <button onClick={() => setCount((c) => c + 1)}>Increment</button>
      <ExpensiveComponent number={10} />
    </div>
  );
}

Benefit: ExpensiveComponent only re-runs the number * number logic if number changes.


📌 useCallback

useCallback memoizes a function definition so that it doesn't get recreated on every render.

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

function Child({ onClick }) {
  console.log("Child rendered");
  return <button onClick={onClick}>Click Me</button>;
}

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount((c) => c + 1)}>Increment</button>
      <Child onClick={handleClick} />
    </div>
  );
}

Benefit: Prevents unnecessary re-renders of Child by keeping handleClick reference stable.


🛠 Use Cases in Real Apps

  • React: useMemo() and React.memo() prevent unnecessary re-renders
  • Math-heavy computations: Caching expensive calculations
  • Form validations: Storing results of validations for same inputs
  • APIs: Caching responses in memory/localStorage

🚫 When Not to Use Memoization

  • If your function has side effects (like network requests, writing to disk)
  • If inputs are almost always unique (caching won't help)
  • If memory usage is a concern (cache can grow large)

🙏 Thank You!

Thank you for reading!

I hope you enjoyed this post. If you did, please share it with your network and stay tuned for more insights on software development. I'd love to connect with you on LinkedIn or have you follow my journey on HashNode for regular updates.

Happy Coding!
Mitesh Kukdeja

2
Subscribe to my newsletter

Read articles from Mitesh Kukdeja directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mitesh Kukdeja
Mitesh Kukdeja

Turning ideas into smooth, scalable mobile experiences — one line of code at a time. Hi, I’m Mitesh Kukdeja — a passionate React Native developer with 2+ years of hands-on experience building cross-platform apps that delight users and deliver results. From health and fitness platforms to job boards and music contest apps, I’ve helped bring a wide range of product visions to life. What sets me apart is my obsession with clean, reusable code and user-centric UI/UX. I specialize in React Native, TypeScript, Redux Toolkit, Firebase, and REST API integration—making sure every app I build is responsive, secure, and ready for scale. I’ve also deployed apps to both the Play Store and App Store, managing the full release cycle. My projects have included integrating real-time features like video conferencing (Agora), personalized push notifications, and advanced security implementations for enterprise clients like Godrej. Whether it’s debugging a performance bottleneck or designing a scalable component architecture, I’m all in. My goal is to keep solving meaningful problems through technology while collaborating with creative minds. I thrive in fast-paced environments where innovation and impact matter. If you’re building something exciting in mobile or looking for a tech partner who values quality and performance — let’s connect!