useBrowse
Collection browse hook - filter-driven, paginated, typed over your document, with auto-emitted analytics events.
useBrowse<TDoc> is the collection page hook. It is identical to useSearch in its return shape but has no text query - it drives results entirely through filters and sort. Use it for category pages, landing pages, and any browse surface where the visitor is filtering rather than typing.
The hook auto-emits a search analytics event (with q: "*") on each result, and returns trackProductClicked tied to the current queryId.
Signature
function useBrowse<TDoc = KelpDocumentBase>(opts: UseBrowseOptions): UseBrowseResult<TDoc>Options
interface UseBrowseOptions {
collection: string;
facets?: string[];
perPage?: number;
sort?: SortItem[];
fields?: string[];
/** Auto-emit a `search` analytics event on each result. Default true. */
trackSearch?: boolean;
}| Option | Default | Notes |
|---|---|---|
collection | - | Required. The Kelp collection to browse. |
facets | - | Facet fields to count. Omit to count all configured facet attributes. |
perPage | 20 | Results per page. |
sort | - | Sort order. Array of { field, direction } applied in sequence. |
fields | - | Restrict returned document fields (projection). |
trackSearch | true | Set to false to opt out of automatic analytics events. |
Return value
{
// Pagination
page: number;
setPage: (p: number) => void;
perPage: number;
setPerPage: (n: number) => void;
totalPages: number;
// Results
hits: KelpHit<TDoc>[];
facetCounts: KelpFacetCount[];
found: number;
result: KelpSearchResponse<TDoc> | null;
// Filter state
filters: KelpFilters;
setFilters: (filters: KelpFilters) => void;
toggleFilter: (field: string, value: string) => void;
isFilterActive: (field: string, value: string) => boolean;
clearFilters: () => void;
// Status
status: 'idle' | 'loading' | 'success' | 'error';
isLoading: boolean;
error: Error | null;
// Analytics
trackProductClicked: (objectId: string) => void;
}Basic collection page
import { useBrowse } from '@kelpclick/client/react';
import type { KelpDocumentBase } from '@kelpclick/client';
interface Product extends KelpDocumentBase {
title: string;
handle: string;
vendor: string;
prices?: number[];
}
export function CollectionPage() {
const {
hits,
facetCounts,
found,
page,
setPage,
totalPages,
isFilterActive,
toggleFilter,
clearFilters,
filters,
isLoading,
error,
trackProductClicked,
} = useBrowse<Product>({
collection: 'products',
perPage: 24,
sort: [{ field: 'variantsInStockPercentage', direction: 'desc' }],
});
const activeCount = filters.reduce((n, f) => n + f.values.length, 0);
return (
<div>
<p>{isLoading ? 'Loading...' : `${found.toLocaleString()} products`}</p>
{error && <p>Failed to load. Try again.</p>}
<aside>
{activeCount > 0 && (
<button onClick={clearFilters}>Clear all ({activeCount})</button>
)}
{facetCounts.map((facet) => (
<div key={facet.field}>
<h4>{facet.field}</h4>
<ul>
{facet.counts.map(({ value, count }) => (
<li key={value}>
<label>
<input
type="checkbox"
checked={isFilterActive(facet.field, value)}
onChange={() => toggleFilter(facet.field, value)}
/>
{value} ({count})
</label>
</li>
))}
</ul>
</div>
))}
</aside>
<section>
<ul>
{hits.map((h) => (
<li key={h.document.id}>
<a
href={`/products/${h.document.handle}`}
onClick={() => trackProductClicked(h.document.id)}
>
{h.document.title}
</a>
</li>
))}
</ul>
{hits.length === 0 && !isLoading && <p>No products found.</p>}
<div>
<button disabled={page <= 1} onClick={() => setPage(page - 1)}>Prev</button>
<span>{page} / {totalPages}</span>
<button disabled={page >= totalPages} onClick={() => setPage(page + 1)}>Next</button>
</div>
</section>
</div>
);
}Emitting a collection_viewed event
useBrowse auto-emits a search event per result. To also emit a collection_viewed event (for collection-level attribution), pull useKelpAnalytics and fire it once per distinct result set:
import { useBrowse, useKelpAnalytics } from '@kelpclick/client/react';
import { useEffect, useRef } from 'react';
export function CollectionPage({ collectionId }: { collectionId: string }) {
const analytics = useKelpAnalytics();
const { hits, result, isLoading, trackProductClicked } = useBrowse<Product>({
collection: 'products',
});
// Emit collection_viewed once per distinct queryId.
const lastQueryId = useRef<string | undefined>(undefined);
useEffect(() => {
if (isLoading) return;
const queryId = result?.queryId;
if (queryId === lastQueryId.current) return;
lastQueryId.current = queryId;
analytics.trackCollectionViewed({
collection: 'products',
objectId: collectionId,
queryId,
});
}, [analytics, isLoading, result?.queryId, collectionId]);
// ...render
}Sorting
Pass a sort array. Multiple keys are applied in order:
const { hits } = useBrowse<Product>({
collection: 'products',
sort: [
{ field: 'variantsInStockPercentage', direction: 'desc' },
{ field: 'title', direction: 'asc' },
],
});Operator filters
toggleFilter handles equality (=) clauses for facet checkboxes. For range or comparison filters, set the array directly with setFilters:
const { setFilters } = useBrowse<Product>({ collection: 'products' });
// Show only products priced between $20 and $100
setFilters([
{ field: 'price', op: '>=', values: ['20'] },
{ field: 'price', op: '<=', values: ['100'] },
]);Filter clauses are AND-ed together. Multiple values within a single = clause are treated as OR (IN-list). See Filtering for the full filter reference.
Related
- useSearch - same shape with a text query and debouncing
- Filtering - filter operators and combinations
- Search - underlying browse API
- KelpProvider - required wrapper
useSearch
Debounced search hook with pagination, facet selection, request cancellation, stale-response guarding, and auto-emitted analytics events.
Context hooks
useKelpClient, useKelpIdentity, useKelpAnalytics, useKelpQuery, and useDebouncedValue - the lower-level hooks exported from @kelpclick/client/react.