Skip to lesson content

PROJECT 3 · LESSON 9 OF 18

Keep a guest cart after refresh

Restore browser data after hydration and handle corrupt storage.

  • localStorage
  • effects
  • hydration
  • validation

Your workspace: edushop

Continue from lesson 8: Share the cart across routes. Keep existing files; create or replace the complete files listed below.

Extract the ZIP, open its project folder, and run npm install. Database lessons also need the .env.local setup described below. Checkpoints never contain credentials or node_modules.

1. Understand the problem and the concepts

Why we need this feature

Shared state solves disagreement between components, but a full refresh creates a new component tree. Persistence needs a separate storage location and a careful order for restoring and saving data.

localStorage belongs to the browser, even though Client Components can be prerendered on the server. Both initial renders start with an empty cart; an effect restores the stored data after hydration.

The ready flag prevents the initial empty array from overwriting a saved cart. Browser storage is untrusted input, so validate its shape. This cart is per browser, not per account; private saved carts are a later extension.

Understand the two initial renders

A Client Component can participate in server prerendering. The server does not have localStorage. The initial browser render must also agree with the server-generated UI for hydration to work predictably. Starting with [] in both places gives them the same initial state.

After hydration, the restoration effect can read localStorage in the browser. It replaces lines with validated stored data and sets ready to true. The cart page uses ready to show Restoring cart rather than briefly telling the shopper their saved cart is empty.

Why restoring and saving need a gate

The persistence effect also runs after a render. Without the ready check, it could save the initial empty array before restoration has completed, destroying the previous cart. With the gate, the first save is skipped. Once restored state and ready are committed, the effect writes the restored or subsequently updated lines.

JSON.stringify serializes the array into a storage string. JSON.parse reconstructs a value, but that value is not necessarily a valid cart. The reader checks for an array, unique string IDs, integer quantities and the allowed range. A malformed JSON string is caught and treated as an empty cart.

Know the limits of browser storage

localStorage is scoped to the website origin and browser profile. It is not associated with a signed-in account. A different device does not see the same cart. The example also does not subscribe to storage events, so two open tabs do not synchronize their in-memory views automatically.

Storage can fail because of browser settings or capacity. The catch blocks allow shopping to continue in memory. A production UI could explain that saving is unavailable, but a storage exception should not crash the entire storefront.

The ready guard also prevents AddToCart from racing with restoration. If a shopper added an item before the saved state arrived, a later restore could overwrite the new choice. Disable that operation until the initial restore finishes.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. Server and initial browser render use an empty cart with ready=false.

  2. The browser effect reads and validates saved JSON.

  3. The provider commits restored lines and ready=true.

  4. Later line changes trigger the save effect, which writes the new array.

Trace a refresh with two notebooks

  1. Before refresh, storage contains [{"productId":"p1","quantity":2}].
  2. The new provider begins with [] but does not save because ready is false.
  3. readCart parses the string, validates the p1 line, and returns it.
  4. The restored render displays two notebooks. The save effect now writes that same valid state rather than an empty cart.

3. Build it, one file at a time

  1. Replace the provider and AddToCart with these versions.
  2. Add a notebook and refresh. Then edit the storage value to invalid JSON in browser developer tools and refresh again.
  3. Storage failures fall back to an in-memory cart. This lesson does not synchronize tabs.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

components/cart-provider.tsx

This is the single owner of shared client cart state and its permitted operations.

components/cart-provider.tsx
"use client";
import {
  createContext,
  useContext,
  useEffect,
  useState,
  type ReactNode,
} from "react";
import { changeQuantity, type CartLine } from "@/lib/cart";
type Cart = {
  lines: CartLine[];
  ready: boolean;
  setQuantity: (id: string, n: number) => void;
  add: (id: string) => void;
  clear: () => void;
};
const Context = createContext<Cart | null>(null);
const KEY = "edushop-cart-v1";
function readCart(): CartLine[] {
  try {
    const value: unknown = JSON.parse(localStorage.getItem(KEY) ?? "[]");
    if (!Array.isArray(value)) return [];
    const seen = new Set<string>();
    return value
      .filter((line): line is CartLine => {
        if (
          !line ||
          typeof line.productId !== "string" ||
          !Number.isInteger(line.quantity) ||
          line.quantity < 1 ||
          line.quantity > 10 ||
          seen.has(line.productId)
        )
          return false;
        seen.add(line.productId);
        return true;
      })
      .slice(0, 50);
  } catch {
    return [];
  }
}
export function CartProvider({ children }: { children: ReactNode }) {
  const [lines, setLines] = useState<CartLine[]>([]);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    // Synchronize browser storage after hydration; never read it during SSR.
    setLines(readCart());
    setReady(true);
  }, []);
  useEffect(() => {
    if (ready) {
      try {
        localStorage.setItem(KEY, JSON.stringify(lines));
      } catch {
        /* Cart still works in memory. */
      }
    }
  }, [lines, ready]);
  function setQuantity(id: string, n: number) {
    if (ready && Number.isFinite(n))
      setLines((old) => changeQuantity(old, id, n));
  }
  function add(id: string) {
    if (ready)
      setLines((old) =>
        changeQuantity(
          old,
          id,
          (old.find((l) => l.productId === id)?.quantity ?? 0) + 1,
        ),
      );
  }
  return (
    <Context.Provider
      value={{ lines, ready, setQuantity, add, clear: () => setLines([]) }}
    >
      {children}
    </Context.Provider>
  );
}
export function useCart() {
  const value = useContext(Context);
  if (!value) throw new Error("CartProvider is missing");
  return value;
}

Read the code

  1. Context starts with null. CartProvider supplies lines and update functions to its descendants; useCart throws a useful error if that provider is missing.
  2. add uses the existing quantity from a functional update. setQuantity delegates the pure array transformation. clear requests a new empty array.
  3. The provider is mounted in the shared layout so internal route transitions can reuse the same state. Context itself does not persist data.
  4. readCart parses unknown browser storage, rejects malformed lines and deduplicates IDs. It runs from an effect after hydration rather than during server rendering.
  5. ready begins false. The save effect skips its first pass, avoiding overwriting saved data with the initial empty array.
  6. After restoration, the second effect writes subsequent state changes. Storage failures are caught so the in-memory cart remains usable.

components/add-to-cart.tsx

This gives a product card a small client-side control without moving the whole catalog into client state.

components/add-to-cart.tsx
"use client";
import { useCart } from "./cart-provider";
export default function AddToCart({ id }: { id: string }) {
  const { add, ready } = useCart();
  return (
    <button disabled={!ready} onClick={() => add(id)}>
      Add to cart
    </button>
  );
}

Read the code

  1. The id prop is a plain product identifier passed by the parent. The component gets the add operation from useCart.
  2. The click handler calls add only when the user activates the button. Passing add(id) directly as the handler value would call it during rendering instead.
  3. In the persistence version, ready disables the button until stored cart data has been restored.

app/cart/page.tsx

This renders cart choices and derives their display values from the catalog.

app/cart/page.tsx
"use client";
import { products } from "@/lib/products";
import { money } from "@/lib/money";
import { useCart } from "@/components/cart-provider";
export default function CartPage() {
  const { lines, ready, setQuantity, clear } = useCart();
  if (!ready) return <p>Restoring cart…</p>;
  const total = lines.reduce(
    (sum, line) =>
      sum +
      (products.find((p) => p.id === line.productId)?.price ?? 0) *
        line.quantity,
    0,
  );
  return (
    <>
      <h1>Your cart</h1>
      {lines.map((line) => {
        const product = products.find((p) => p.id === line.productId);
        return (
          <article key={line.productId}>
            <h2>{product?.name ?? "Unavailable product"}</h2>
            <label>
              Quantity{" "}
              <input
                type="number"
                min="1"
                max="10"
                value={line.quantity}
                onChange={(e) => {
                  const n = Number(e.target.value);
                  if (Number.isInteger(n) && n > 0)
                    setQuantity(line.productId, n);
                }}
              />
            </label>
            <p>{money((product?.price ?? 0) * line.quantity)}</p>
            <button onClick={() => setQuantity(line.productId, 0)}>
              Remove
            </button>
          </article>
        );
      })}
      {!lines.length && (
        <p>Your cart is empty. Visit Products to add an item.</p>
      )}
      <p>Total: {money(total)}</p>
      {!!lines.length && <button onClick={clear}>Clear cart</button>}
    </>
  );
}

Read the code

  1. useCart replaces page-local state with the shared provider. The page, product buttons and header read the same lines.
  2. Each line looks up its product by ID and multiplies its unit price by quantity. reduce adds those line amounts into the displayed total.
  3. Quantity and remove controls request a new array rather than mutating existing state. Missing products have a fallback label; checkout later rejects unavailable choices.
  4. The ready branch displays restoration feedback before treating the cart as genuinely empty.

4. Run it and check your result

  • A refresh preserves quantities.
  • Invalid storage does not crash the page.
  • Clearing and refreshing leaves an empty cart.

5. Predict, change and observe

In browser storage, set the quantity to -4 or create two p1 entries. Reload and inspect the cart.

Compare your prediction with the expected result

What you should observe

Invalid quantities are rejected and duplicate product IDs do not become duplicate cart lines.

Why it happens

Parsing JSON checks syntax only. Runtime validation checks whether the data is acceptable for this application.

6. Troubleshoot with evidence

A common mistake

Do not read localStorage at module scope or save the initial empty cart before restoration finishes.

localStorage is not defined.

Likely cause: Browser storage was accessed on the server or at module initialization.

Check and correct: Keep the read inside the client effect or a function called by that effect.

A saved cart disappears immediately after refresh.

Likely cause: The initial empty state was persisted before restoration.

Check and correct: Keep the ready gate around saving and disable add operations until restoration completes.

7. Practice and explain it back

Your independent task

Add a message explaining that the guest cart is saved on this device.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why not read localStorage directly in the useState initializer?

The component may render on the server, where that API is unavailable. A browser-only initializer can also create an initial hydration mismatch.

Is a restored quantity trustworthy at checkout?

No. The shopper controls browser storage. Checkout must validate quantities and retrieve authoritative prices and stock on the server.