# 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";
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://search.docs.reactify.com.au/hooks/usesortby.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
