DEV Community

Cover image for How to do in-memory Caching using ReactJS
Vijendra-Tech
Vijendra-Tech

Posted on

How to do in-memory Caching using ReactJS

In some cases where we don't require to call multiple API calls for the same result.

Using a Map object can be more efficient than using a plain object as a cache, especially when dealing with a large amount of data, as Map objects are optimized for handling key-value pairs. Additionally, using a hash map allows for faster lookup times than using an array or other data structures for caching.

In a real-world application, you may want to implement more advanced caching strategies or use a dedicated caching solution like Redis or Memcached.

But for the simple use case, we can use the in-memory cache mechanism.

Here is example

//using cahed object
import React, { useEffect, useState } from 'react';

const cache = {};

function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://example.com/api/data');
      const jsonData = await response.json();
      setData(jsonData);
    };

    // Check if the data is in the cache
    if (cache['cachedData']) {
      setData(cache['cachedData']);
    } else {
      fetchData();
    }
  }, []);

  useEffect(() => {
    // Store the data in the cache
    cache['cachedData'] = data;
  }, [data]);

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default App;
//using Map
import React, { useEffect, useState } from 'react';

const cache = new Map();

function App() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://example.com/api/data');
      const jsonData = await response.json();
      setData(jsonData);
    };

    // Check if the data is in the cache
    if (cache.has('cachedData')) {
      setData(cache.get('cachedData'));
    } else {
      fetchData();
    }
  }, []);

  useEffect(() => {
    // Store the data in the cache
    cache.set('cachedData', data);
  }, [data]);

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)