useSearch
Debounced search hook with pagination, facet selection, request cancellation, stale-response guarding, and auto-emitted analytics events.
useSearch<TDoc> is the primary hook for building search UIs. It handles debouncing, pagination, facet selection, request cancellation, and stale-response guarding. It auto-emits a search analytics event on each result and returns a trackProductClicked function tied to the current queryId.
When the query string is blank, the hook searches "*" (match-all) so an empty box browses the whole collection rather than returning nothing.
Signature
function useSearch<TDoc = KelpDocumentBase>(opts: UseSearchOptions): UseSearchResult<TDoc>Options
interface UseSearchOptions {
collection: string;
facets?: string[];
perPage?: number;
sort?: SortItem[];
fields?: string[];
initialQuery?: string;
debounceMs?: number;
/** Auto-emit a `search` analytics event on each result. Default true. */
trackSearch?: boolean;
}| Option | Default | Notes |
|---|---|---|
collection | - | Required. The Kelp collection to search. |
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 the returned document fields (projection). |
initialQuery | '' | Starting value of the query state. |
debounceMs | 200 | Milliseconds to wait after the last keystroke before firing the request. |
trackSearch | true | Set to false to opt out of automatic search analytics events. |
Return value
The hook returns everything from useKelpQuery plus query-specific fields:
{
// Query state
query: string;
setQuery: (q: string) => void;
debouncedQuery: string;
// 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;
}trackProductClicked emits a product_clicked event pre-filled with the queryId from the most recent completed search, so every click is automatically attributed to the query that produced it.
Basic search box
import { useSearch } from '@kelpclick/client/react';
import type { KelpDocumentBase } from '@kelpclick/client';
interface Product extends KelpDocumentBase {
title: string;
handle: string;
vendor: string;
}
export function SearchBox() {
const {
query,
setQuery,
hits,
found,
page,
setPage,
totalPages,
isLoading,
error,
trackProductClicked,
} = useSearch<Product>({
collection: 'products',
perPage: 24,
fields: ['id', 'title', 'handle', 'vendor'],
});
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search products..."
/>
{isLoading && <p>Searching...</p>}
{error && <p>Search failed. Try again.</p>}
{!isLoading && <p>{found.toLocaleString()} results</p>}
<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 results.</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>
</div>
);
}Facet filtering
toggleFilter and isFilterActive manage equality (=) clauses - the facet checkbox case. Calling toggleFilter automatically resets the page to 1.
export function VendorFacet() {
const { facetCounts, isFilterActive, toggleFilter } = useSearch<Product>({
collection: 'products',
facets: ['vendor', 'productType'],
});
const vendor = facetCounts.find((f) => f.field === 'vendor');
return (
<ul>
{vendor?.counts.map(({ value, count }) => (
<li key={value}>
<label>
<input
type="checkbox"
checked={isFilterActive('vendor', value)}
onChange={() => toggleFilter('vendor', value)}
/>
{value} ({count})
</label>
</li>
))}
</ul>
);
}For operator filters (range, comparison), set the array directly with setFilters:
// Price range filter
setFilters([
{ field: 'price', op: '>=', values: ['20'] },
{ field: 'price', op: '<=', values: ['100'] },
]);Sort and fields
const { hits } = useSearch<Product>({
collection: 'products',
sort: [{ field: 'title', direction: 'asc' }],
fields: ['id', 'title', 'handle', 'prices'],
});Highlights
Each hit carries a highlights array. Snippets may contain <mark> tags around matched terms:
{hits.map((h) => (
<div key={h.document.id}>
<a href={`/products/${h.document.handle}`}>{h.document.title}</a>
{h.highlights.map((hl) => (
<p
key={hl.field}
dangerouslySetInnerHTML={{ __html: hl.snippet }}
/>
))}
</div>
))}Only set dangerouslySetInnerHTML on highlight snippets from your own trusted Kelp index. Sanitize if the indexed content originates from user input.
Opting out of auto analytics
useSearch auto-emits a search event after each successful fetch. To emit events yourself (or suppress them):
const { hits } = useSearch<Product>({
collection: 'products',
trackSearch: false, // disable automatic search events
});How debouncing and cancellation work
- The raw
querystate updates on every keystroke.debouncedQueryupdates afterdebounceMsof silence (default 200 ms). - Each fetch is made with an
AbortController. When a new fetch starts before the previous one completes, the previous one is aborted and its result is discarded, preventing stale results from appearing. - Cancelled fetches are not surfaced as errors.
Related
- useBrowse - the same return shape without a text query
- Context hooks -
useKelpQuery,useKelpAnalytics - Search - underlying search and filter API
- KelpProvider - required wrapper