DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted 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.

Top comments (0)