Skip to main content

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

useFilters

Provides access to the centralized filter state managed by FilterProvider. Supports text search, multi-tag and multi-category selection, sorting, location-based filtering, and automatic URL synchronization for shareable/bookmarkable filter states.

Source: template/hooks/use-filters.ts Context: template/components/filters/context/filter-context.tsx State logic: template/components/filters/hooks/use-filter-state.ts

Usage

import { useFilters } from '@/hooks/use-filters';

function SearchBar() {
const { searchTerm, setSearchTerm } = useFilters();

return (
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search items..."
/>
);
}
Provider Required

useFilters must be called within a <FilterProvider>. Calling it outside the provider throws:

Error: useFilters must be used within a FilterProvider

FilterProvider Setup

import { FilterProvider } from '@/components/filters/context/filter-context';

function ListingPage({ initialTag, initialCategory }) {
return (
<FilterProvider
initialTag={initialTag}
initialCategory={initialCategory}
initialSortBy="popularity"
>
<SearchBar />
<TagFilter />
<CategoryFilter />
<ItemGrid />
</FilterProvider>
);
}

Provider Props

PropTypeDefaultDescription
childrenReactNode--Child components
initialTagstring | nullnullPre-selected tag from route params
initialCategorystring | nullnullPre-selected category from route params
initialSortBystring'popularity'Initial sort option

Return Values

State

PropertyTypeDescription
searchTermstringCurrent search query
selectedTagsTagId[]Array of selected tag IDs (multi-select)
selectedCategoriesCategoryId[]Array of selected category IDs
sortBySortOptionCurrent sort option
selectedTagTagId | nullSingle selected tag (navigation mode)
selectedCategoryCategoryId | nullSingle selected category (navigation mode)
isFiltersLoadingbooleanTrue during filter URL sync transitions
locationFilterLocationFilterStateCurrent location filter settings

Setters

MethodSignatureDescription
setSearchTerm(term: string) => voidUpdate search query and sync URL
setSelectedTagsDispatch<SetStateAction<TagId[]>>Set tag selection
setSelectedCategoriesDispatch<SetStateAction<CategoryId[]>>Set category selection
setSortByDispatch<SetStateAction<SortOption>>Set sort option
setSelectedTagDispatch<SetStateAction<TagId | null>>Set single navigation tag
setSelectedCategoryDispatch<SetStateAction<CategoryId | null>>Set single navigation category

Tag Actions

MethodSignatureDescription
addSelectedTag(tagId: TagId) => voidAdd a tag to the selection
removeSelectedTag(tagId: TagId) => voidRemove a tag from the selection
toggleSelectedTag(tagId: TagId) => voidToggle a tag on/off

Category Actions

MethodSignatureDescription
addSelectedCategory(categoryId: string) => voidAdd a category to the selection
removeSelectedCategory(categoryId: string) => voidRemove a category
toggleSelectedCategory(categoryId: string) => voidToggle a category (exclusive: selects only this one, or deselects if already active)
clearSelectedCategories() => voidClear all category selections

Location Actions

MethodSignatureDescription
setNearMe(coords: NearMeCoordinates | null) => voidSet or clear geolocation-based filter
setLocationRadius(radius: number) => voidUpdate radius for Near Me filter (km)
setLocationCity(city: string | null) => voidFilter by city name
setLocationCountry(country: string | null) => voidFilter by country
clearLocationFilter() => voidClear all location filters

Reset

MethodSignatureDescription
clearAllFilters() => voidReset all filters, search, sort, and location to defaults

Types

type SortOption = 'popularity' | 'name-asc' | 'name-desc' | 'date-desc' | 'date-asc';
type CategoryId = string;
type TagId = string;

interface NearMeCoordinates {
latitude: number;
longitude: number;
radius: number; // kilometers
}

interface LocationFilterState {
nearMe?: NearMeCoordinates;
city?: string;
country?: string;
sortByDistance?: boolean;
}

URL Synchronization

All filter changes are automatically reflected in the URL via useFilterURLSync. This enables:

  • Bookmarkable filter states -- users can save filtered views
  • Shareable links -- sending a URL preserves the exact filter configuration
  • Browser back/forward -- navigation respects filter history

URL parameters include: tags, categories, q (search), nearLat, nearLng, radius, city, country.

Usage: Multi-Tag Filtering

function TagCloud({ tags }) {
const { selectedTags, toggleSelectedTag } = useFilters();

return (
<div className="flex flex-wrap gap-2">
{tags.map((tag) => (
<button
key={tag.id}
onClick={() => toggleSelectedTag(tag.id)}
className={selectedTags.includes(tag.id) ? 'bg-primary' : 'bg-gray-200'}
>
{tag.name}
</button>
))}
</div>
);
}

Usage: Location Filtering

function NearMeButton() {
const { setNearMe, clearLocationFilter, locationFilter } = useFilters();

const handleNearMe = () => {
navigator.geolocation.getCurrentPosition((pos) => {
setNearMe({
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
radius: 50,
});
});
};

return locationFilter.nearMe
? <button onClick={clearLocationFilter}>Clear Location</button>
: <button onClick={handleNearMe}>Near Me</button>;
}

Usage: Reset All Filters

function ClearFiltersButton() {
const { clearAllFilters, selectedTags, selectedCategories, searchTerm } = useFilters();
const hasActiveFilters = selectedTags.length > 0 || selectedCategories.length > 0 || searchTerm;

if (!hasActiveFilters) return null;

return <button onClick={clearAllFilters}>Clear All Filters</button>;
}