CodingNic

Build the Wishlist

Create the Wishlist Context

Build the Wishlist 10 min read

Create the Wishlist Context

Create the Wishlist Context

Create the shared client-side state for saved movie ids. Keep the context small so every consumer gets a clear contract.

Step 1 — Mark the file as client-side

Create context/WishlistContext.tsx and begin with:

typescript
"use client";

The context will use React state and later the browser’s localStorage API.

Step 2 — Define the context contract

Create an interface with ids, isSaved, toggle, and ready.

typescript
interface WishlistContextValue {
  ids: number[];
  isSaved: (id: number) => boolean;
  toggle: (id: number) => void;
  ready: boolean;
}

The ready flag will be used when persistence is introduced.

Step 3 — Create the context and provider state

Create the context with a null default, then create ids and ready inside the provider.

typescript
const [ids, setIds] = useState<number[]>([]);
const [ready, setReady] = useState(false);

The provider should eventually expose the same four values through the context.

Step 4 — Add isSaved and toggle

Use useCallback for both helpers. isSaved checks inclusion; toggle either removes an existing id or appends a new one.

typescript
const isSaved = useCallback((id: number) => ids.includes(id), [ids]);

Checkpoint

WishlistContext.tsx compiles and exposes the shared wishlist contract. No heart has changed behavior yet because no component consumes the context.