# @snizu/react

Source: https://snizu.dev/docs/storefronts/react

## Install it [#install-it]

```sh title="Terminal"
npm i @snizu/react @snizu/storefront
```

Put the provider in a client component near the top of the tree. It takes everything `createStorefront` does, or a `client` you made yourself:

```tsx title="shop.tsx"
"use client";
import { StorefrontProvider, useCart, useMoney, useProduct } from "@snizu/react";

export function Shop({ children }) {
  return (
    <StorefrontProvider publishableKey="pk_…" locale="ar" country="EG">
      {children}
    </StorefrontProvider>
  );
}

function BuyButton({ handle }) {
  const { data: product, isLoading, error } = useProduct(handle);
  const { add, isUpdating } = useCart();
  const money = useMoney();
  if (isLoading) return <p>…</p>;
  if (error) return <p>{error.message}</p>;
  const variant = product.variants[0];
  return (
    <button disabled={isUpdating} onClick={() => add({ productId: product.id, variantId: variant.id })}>
      {money(variant.price)}
    </button>
  );
}
```

## The hooks [#the-hooks]

<Fields>
<Field name="useProduct(handle, options?)">
A product.
</Field>

<Field name="useProducts(query?, options?)">
A page of products. For the next, pass `page.next_cursor` as `cursor`.
</Field>

<Field name="useInfiniteProducts(query?), useInfiniteCollection(handle, query?)">
A list that grows a page at a time: `items`, `hasMore`, `loadMore()`, `isLoadingMore`.
</Field>

<Field name="useCollections(query?)">
A page of the store's collections.
</Field>

<Field name="useCollection(handle, query?, options?)">
A collection and a page of its products.
</Field>

<Field name="useRecommendations(handle, query?)">
Products to show with one: related, or add-ons with `intent: "complementary"`.
</Field>

<Field name="useAvailability(variantIds)">
Whether variants can be bought now, read in the browser while the page stays cached.
</Field>

<Field name="useSearch(query, options?)">
Search as someone types: it waits for a pause (`debounceMs`, 250 by default) and asks nothing for an empty `q`.
</Field>

<Field name="useSuggestions(q)">
What a search box suggests as someone types, from two characters.
</Field>

<Field name="useCart()">
`cart`, `itemCount`, `isLoading`, `isUpdating`, `error`, and `add`, `update`, `remove`, `applyDiscountCode`, `removeDiscountCode`, `apply`, `refresh`.
</Field>

<Field name="useCheckoutUrl()">
The store's hosted checkout for this cart, or `null` before anything was added.
</Field>

<Field name="useCustomer()">
`customer`, `isLoading`, `error`, and `signIn`, `signUp`, `requestCode`, `verifyCode`, `signOut`.
</Field>

<Field name="useOrders(query?), useOrder(id)">
The signed-in customer's orders.
</Field>

<Field name="useWishlist()">
The signed-in customer's wishlist, with `has`, `save` and `remove`.
</Field>

<Field name="useStoreProfile(), useStoreBrand(), usePolicies(), usePolicy(kind)">
The store's details, brand and legal pages.
</Field>

<Field name="useMoney()">
A function that formats amounts in the provider's language; `null` is an empty string.
</Field>

<Field name="useStorefront()">
The client, for what no hook covers.
</Field>
</Fields>

Read hooks answer `{ data, isLoading, isFetching, error, refetch }` and take `{ enabled, initialData }`. Pass what a server component already read as `initialData`, and the cart the server read as the provider's `initialCart`, and the first paint doesn't load. A read nobody shows any more, because its component unmounted or the search moved on, is stopped. A new `locale` or `country` on the provider changes its client; a new `publishableKey` or `apiUrl` makes a new one.

## Cart changes [#cart-changes]

A change shows at once and goes to the API one at a time, in order. If one fails it rolls back, its promise rejects and `error` says why, and any made after it still show.

- A new line counts in `itemCount` at once, the very first add too, and is drawn when the answer is back, because it has no name or price until then. Show `itemCount` on a cart badge.
- A discount code shows when the answer is back, since only the API can work out what it does.
- A line with a booking, a selling plan or answers to the product's questions is always a line of its own.

Make every other change through `apply`, so each component showing the cart sees it: `apply((client) => client.cart.setNote("Gift wrap"))`. The cart is read again when the shopper comes back to the page, so after paying on the hosted checkout it clears by itself.

## Signing in and out [#signing-in-and-out]

Doing either starts every read afresh, since a cart and prices can depend on who's asking. An answer still on its way for the last customer is thrown away.

The first render matches the server's. With `initialCustomer` on the provider, both show that customer, or nobody for `null`. Without it, `useCustomer` reads `isLoading` until the browser knows, so a signed-in reload never flashes "Sign in" or breaks hydration.

Where the store approves new accounts, `signUp`, and `verifyCode` for a new shopper, answer `{ status: "pending" }` and nobody is signed in:

```tsx title="sign-up.tsx"
import { isAccountRequest } from "@snizu/storefront";

const result = await signUp({ email, password });
if (isAccountRequest(result)) setNotice("The store reviews new accounts. We'll email you.");
```

## In Next.js [#in-nextjs]

Read the catalog in server components with [`@snizu/storefront/server`](/docs/storefronts/storefront-client#on-a-server), and use the hooks for what changes as someone types or clicks: the cart drawer, search suggestions. To share one cart between them, keep the tokens in cookies both sides read:

```tsx title="providers.tsx"
"use client";
import { browserCookieStorage } from "@snizu/storefront";

<StorefrontProvider publishableKey={key} locale={locale} storage={browserCookieStorage()}>
```

and on the server `createServerStorefront({ …, cookies: await cookies(), cookieOptions: { httpOnly: false } })`. That's how the [Next.js starter](/docs/storefronts/nextjs-starter) is built.