DEV Community

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

Posted on

3

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay