HapplyUI

Hooks

useFilterBar

A React hook that eliminates the boilerplate of wiring FilterDropdown and AppliedFilters together. It manages local working selections, syncs them with committed filter state, and provides handlers for apply, remove, and reset — so the page only needs to define filter configs and plug in the returned props.


Installation

bunx @happlyui/cli@latest add use-filter-bar

Usage

import { useFilterBar } from "@/hooks/use-filter-bar"

const filterBar = useFilterBar({
  filterKeys: ['status', 'category', 'assignee'],
  filters,
  setFilters,
  setPage,
})

Examples

Basic Usage with FilterDropdown and AppliedFilters

Wire the hook's return values directly to FilterDropdown.Composed and AppliedFilters.Root props.

const FILTER_KEYS = ['types', 'status'] as const;

const filterBar = useFilterBar({
  filterKeys: FILTER_KEYS,
  filters,
  setFilters,
  setPage,
});

<FilterDropdown.Composed
  filters={filterConfigs}
  selected={filterBar.selections}
  onSelectedChange={filterBar.onSelectedChange}
  onApply={filterBar.onApply}
>
  <Button.Root>Filters</Button.Root>
</FilterDropdown.Composed>

<AppliedFilters.Root
  filters={appliedFilterGroups}
  selected={filterBar.applied}
  onRemove={filterBar.onRemove}
  onResetAll={filterBar.onResetAll}
/>

API Reference

useFilterBar

Hook that manages filter state plumbing between a filter dropdown and applied filters display.

PropTypeDefaultDescription
filterKeysreadonly string[]-The keys from the filter state object that this hook manages. Each key must hold a string[] value.
filtersT extends Record<string, unknown>-The committed filter state object (e.g. from context or URL params).
setFiltersReact.Dispatch<React.SetStateAction<T>>-State setter for the committed filters.
setPage(page: number) => void-Optional page setter. Called with 1 after every apply, remove, or reset.

UseFilterBarReturn

Return value of the useFilterBar hook.

PropTypeDefaultDescription
selectionsRecord<string, string[]>-Local working selections. Pass to FilterDropdown.Composed `selected` prop.
onSelectedChange(key: string, values: string[]) => void-Pass to FilterDropdown.Composed `onSelectedChange` prop.
onApply(selected: Record<string, string[]>) => void-Pass to FilterDropdown.Composed `onApply` prop. Commits selections to filter state.
appliedRecord<string, string[]>-Applied filter values derived from committed state. Pass to AppliedFilters.Root `selected` prop.
onRemove(key: string, value: string) => void-Removes a single value from an applied filter. Pass to AppliedFilters.Root `onRemove` prop.
onResetAll() => void-Clears all managed filter keys. Pass to AppliedFilters.Root `onResetAll` prop.
hasAppliedFiltersboolean-Whether any managed filters currently have applied values.

Previous
useFileUpload