Client-Side Caching with Next.js and localStorage

Demonstrate how to cache data on the client side using localStorage in Next.js, including reading and writing data.
import { useEffect, useState } from 'react';

export default function Page() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Check if data is stored in localStorage
    const cachedData = localStorage.getItem('myData');
    if (cachedData) {
      // If data is found, parse it to JSON and set it to state
    } else {
      // If no data is found, fetch new data and cache it
  }, []);

  const fetchDataAndCache = async () => {
    try {
      const response = await fetch('/api/data'); // Fetch data from an API
      const newData = await response.json();
      setData(newData); // Set new data to state
      localStorage.setItem('myData', JSON.stringify(newData)); // Cache the data in localStorage
    } catch (error) {
      console.error('Error fetching data:', error);

  // ... Render your component with the data
  return (
    <div>{data ? <YourComponent data={data} /> : 'Loading...'}</div>
This excerpt of a Next.js page component demonstrates how to use localStorage to cache data on the client side. When the component mounts, it checks for cached data in localStorage. If the data exists, it sets the cached data to state; otherwise, it fetches new data from an API, sets it to state, and caches it in localStorage.
import Head from 'next/head';
import React from 'react';

const YourComponent = ({ data }) => {
  // ... Renders data in your component
  return (
      <pre>{JSON.stringify(data, null, 2)}</pre>

export default YourComponent;
This is a presentational component called YourComponent, which takes the data prop and renders it as a stringified JSON inside a preformatted text block. It's meant to be used as part of the previous code example where it would render the data fetched from the localStorage or an API.
body {
  font-family: 'Arial', sans-serif;

div {
  padding: 20px;
CSS style for the body and div elements. It assigns a font family to the body and adds padding to all div elements, which affects visual presentation of the components in previous examples.