0
0
ReactHow-ToBeginner · 4 min read

How to Cache Data in React: Simple Techniques and Examples

In React, you can cache data by storing it in state or context to avoid repeated fetches during a session. For persistent caching across reloads, use localStorage or sessionStorage combined with React hooks like useEffect to save and load cached data.
📐

Syntax

To cache data in React, you typically use useState to hold the data and useEffect to fetch and store it. For persistent caching, you use localStorage methods inside useEffect.

  • useState(initialValue): Holds cached data in component state.
  • useEffect(callback, dependencies): Runs side effects like fetching and saving data.
  • localStorage.setItem(key, value): Saves data as a string in browser storage.
  • localStorage.getItem(key): Retrieves saved data from browser storage.
jsx
import React, { useState, useEffect } from 'react';

function Component() {
  const [data, setData] = useState(null); // cache in state

  useEffect(() => {
    const cached = localStorage.getItem('myData');
    if (cached) {
      setData(JSON.parse(cached)); // load from cache
    } else {
      fetch('/api/data')
        .then(res => res.json())
        .then(fetchedData => {
          setData(fetchedData); // save to state
          localStorage.setItem('myData', JSON.stringify(fetchedData)); // cache persistently
        });
    }
  }, []);

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Output
<div>{JSON string of data or 'Loading...'}</div>
💻

Example

This example shows how to cache fetched data in React state and localStorage. It first tries to load cached data from localStorage. If none exists, it fetches from an API, saves the data in state, and caches it for future use.

jsx
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    const cachedData = localStorage.getItem('userData');
    if (cachedData) {
      setData(JSON.parse(cachedData));
    } else {
      fetch('https://jsonplaceholder.typicode.com/users/1')
        .then(response => response.json())
        .then(user => {
          setData(user);
          localStorage.setItem('userData', JSON.stringify(user));
        });
    }
  }, []);

  if (!data) return <p>Loading user data...</p>;

  return (
    <div>
      <h2>User Info</h2>
      <p><strong>Name:</strong> {data.name}</p>
      <p><strong>Email:</strong> {data.email}</p>
    </div>
  );
}

export default CachedData;
Output
<h2>User Info</h2><p><strong>Name:</strong> Leanne Graham</p><p><strong>Email:</strong> Sincere@april.biz</p>
⚠️

Common Pitfalls

1. Not parsing or stringifying JSON: localStorage stores only strings, so you must use JSON.stringify when saving and JSON.parse when loading data.

2. Ignoring stale cache: Cached data can become outdated. Consider adding cache expiration or manual refresh.

3. Overusing state updates: Avoid unnecessary state updates that cause extra renders.

js
/* Wrong: storing object directly in localStorage */
localStorage.setItem('data', { name: 'John' }); // stores '[object Object]'

/* Right: stringify before storing */
localStorage.setItem('data', JSON.stringify({ name: 'John' }));

/* Wrong: reading without parsing */
const data = localStorage.getItem('data');
console.log(data.name); // undefined

/* Right: parse after reading */
const dataParsed = JSON.parse(localStorage.getItem('data'));
console.log(dataParsed.name); // 'John'
Output
undefined John
📊

Quick Reference

  • Use useState to hold cached data during component life.
  • Use useEffect to load and save cache on mount.
  • Use localStorage for persistent caching across page reloads.
  • Always JSON.stringify before saving and JSON.parse after loading from localStorage.
  • Consider cache invalidation strategies to keep data fresh.

Key Takeaways

Cache data in React state to avoid repeated fetches during a session.
Use localStorage with JSON stringify/parse for persistent caching across reloads.
Load cached data in useEffect to initialize state efficiently.
Always handle JSON conversion when saving or reading from localStorage.
Plan cache invalidation to prevent showing outdated data.