DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on • Edited on

How to create useMemo hook in vanilla js?

The useMemo hook is also a feature provided by React, and it is not available in vanilla JavaScript. useMemo is used in React functional components to memoize the result of a computation, preventing unnecessary recalculations when the component re-renders.

If you are working with React, you can use the useMemo hook like this:

import React, { useMemo } from 'react';

function MyComponent({ a, b }) {
  const result = useMemo(() => {
    // Your expensive computation logic here
    console.log('Executing expensive computation');
    return a + b;
  }, [a, b]); // Dependencies array

  // Rest of your component code, using the memoized result
  return <div>{result}</div>;
}
Enter fullscreen mode Exit fullscreen mode

If you are looking for a way to memoize values in vanilla JavaScript without using React, you can create a simple memoization function. Here's a basic example using closure:

function useMemo(callback, dependencies) {
  const memoizedValue = function () {
    if (!memoizedValue.cache) {
      memoizedValue.cache = new Map();
    }

    const key = dependencies.join('-');
    if (memoizedValue.cache.has(key)) {
      return memoizedValue.cache.get(key);
    }

    const result = callback();
    memoizedValue.cache.set(key, result);
    return result;
  };

  return memoizedValue;
}

// Example usage:
const a = 1;
const b = 2;
const myMemoizedValue = useMemo(() => {
  console.log('Executing expensive computation');
  return a + b;
}, [a, b]);

console.log(myMemoizedValue()); // Output: Executing expensive computation
console.log(myMemoizedValue()); // Output: (No execution, result retrieved from cache)
Enter fullscreen mode Exit fullscreen mode

Again, keep in mind that this is a simple memoization technique, and if you are working with React, it's recommended to use the useMemo hook provided by React itself.

Support My Work ❤️

If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!

Connect with Me 🌍

Let’s stay connected! You can follow me or reach out on these platforms:

🔹 YouTube – Tutorials, insights & tech content

🔹 LinkedIn – Professional updates & networking

🔹 GitHub – My open-source projects & contributions

🔹 Instagram – Behind-the-scenes & personal updates

🔹 X (formerly Twitter) – Quick thoughts & tech discussions

I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!

Disclaimer

This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.

Top comments (1)

Collapse
 
abbatyya profile image
abbatyya

thank you very much sir, another alternate I make base on yours with same result.

function useMemo(callback, dependencies) {
          const cache = {}
          const memoizeValue = function() {
                const key = dependencies.join('-');
                if(key in cache) {
                    return cache[key];
                }
               return cache[key] =  callback();
            }
            return memoizeValue;
      }
Enter fullscreen mode Exit fullscreen mode