→ cards/05-context-provider

Chapter

05 · Context Provider (context/*.tsx)

UI state sharing only: convenience, not authority; never fetch or mutate data.

Mental Model

  • Context remembers UI state (layout, edit mode), not entity truth.
  • If removing context breaks correctness, context was misused.

File Classification

Layer: UI ergonomics
Directive: "use client"
Runtime: Browser
Prisma: ❌ Never
Server Actions: ❌ Never
Data authority: ❌ Never

Canonical Example

"use client";
import { createContext, useContext, useState } from "react";

type UIState = { isGrid: boolean; toggle: () => void; };
const UIContext = createContext<UIState | null>(null);

export function UIProvider({ children }: { children: React.ReactNode; }) {
const [isGrid, setIsGrid] = useState(false);
return (
<UIContext.Provider value={{ isGrid, toggle: () => setIsGrid((v) => !v) }}>
{children}
</UIContext.Provider>
);
}

export function useUI() {
const ctx = useContext(UIContext);
if (!ctx) throw new Error("useUI must be inside UIProvider");
return ctx;
}

Never Do (and where it belongs)

  • Prisma or fetch → keep in entity/server actions.
  • Permissions/auth → server pages + entity actions.
  • Entity truth/state → server; context is UI-only.