> For the complete documentation index, see [llms.txt](https://search.docs.reactify.com.au/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://search.docs.reactify.com.au/hooks/usesortby.md).

# useSortBy

### Purpose

The useSortBy hook exposes methods and data for sorting results, internally it is used by the [SortBy component](/components/sortby.md).

### Usage

The `sortOptions` field is an array of all available sort options.

The `sortOption` field is the currently selected sort option, by default this is the first sort option.

The `setSortOption` method can be used to change the sort option, you must provide the `handle` value of one of the sort options.

{% tabs %}
{% tab title="ExampleHookUseSortBy" %}

```tsx
import React from "react";
import { useSortBy } from "@usereactify/search";

export const ExampleHookUseSortBy: React.FC = () => {
  const sortByHook = useSortBy();

  const handleSelectChange = React.useCallback((event: React.ChangeEvent<HTMLSelectElement>) => {
    sortByHook.setSortOption(event.target.value);
  }, [sortByHook.setSortOption]);

  return (
    <select
      value={sortByHook.sortOption?.handle}
      onChange={handleSelectChange}
    >
      {sortByHook.sortOptions.map((sortOption) => (
        <option
          key={sortOption.handle}
          value={sortOption.handle}
        >
          {sortOption.name}
        </option>
      ))}
    </select>
  );
};

```

{% endtab %}
{% endtabs %}

### Signature

```typescript
(): {
  /** The currently selected sort option */
  sortOption?: SortOption;
  /** All of the available sort options */
  sortOptions: Array<SortOption>;
  /** Function for changing the current sort option */
  setSortOption: (
    sortOptionHandle: string,
    ignoreHistoryState?: boolean
  ) => void;
};

SortOption = {
  id: string;
  name: string;
  handle: string;
  field: string;
  position: number;
  direction: "desc" | "asc";
  visibility: "all" | "search" | "collection";
};
```
