> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# useQueryRules

> React Hook for setting rule contexts and showing custom data returned by rules.

export const Filter = () => <Tooltip tip="A filter is a condition that limits which records Algolia returns. Filters often use one or more facet-value pairs, such as brand:Apple AND color:red. You can also filter by numeric values, dates, tags, booleans, or geographic constraints." cta="Filtering" href="/doc/guides/managing-results/refine-results/faceting">
    filter
  </Tooltip>;

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
  If you were using React InstantSearch Hooks,
  this v7 documentation applies—just check for [necessary changes](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
  To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).
</Note>

```ts Signature theme={"system"}
const queryRulesApi = useQueryRules({
  // Optional parameters
  trackedFilters?: function
  transformRuleContexts?: function
  transformItems?: function
}
```

## Import

```jsx JavaScript icon=code theme={"system"}
import { useQueryRules } from "react-instantsearch";
```

## About this Hook

The `useQueryRules` Hook lets you interact with Algolia [Rules](/doc/guides/managing-results/rules/rules-overview).

### Rule context

You can use the `useQueryRules` Hook to apply [`ruleContexts`](/doc/api-reference/api-parameters/ruleContexts) based on filters to trigger context-dependent [rules](/doc/guides/managing-results/rules/rules-overview).
You might want to customize the users' experience based on the filters of the search.
For example,
when they visit the "Mobile" category, when they select the "Thriller" genre, and so on.

Rules offer a custom experience based on contexts.
This Hook lets you map a <Filter /> to its associated rule context so you can trigger context-based rules when applying refinements.

### Rule custom data

[Rules](/doc/guides/managing-results/rules/detecting-intent) can return custom data,
which is useful to display banners or recommendations depending on the current search parameters.
The `useQueryRules` Hook expose custom data from rules.

## Examples

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React from "react";
  import { useQueryRules } from "react-instantsearch";

  // Query rule context
  function CustomQueryRuleContext(props) {
    useQueryRules(props);

    return null;
  }

  // Query rule custom data
  function CustomQueryRuleCustomData(props) {
    const { items } = useQueryRules(props);

    return (
      <>
        {items.map(({ title, link, banner }) => (
          <section key={title}>
            <h2>{title}</h2>
            <a href={link}>
              <img src={banner} alt="" />
            </a>
          </section>
        ))}
      </>
    );
  }
  ```

  ```tsx TypeScript theme={"system"}
  import React from "react";
  import { useQueryRules, UseQueryRulesProps } from "react-instantsearch";

  // Query rule context
  function CustomQueryRuleContext(props: UseQueryRulesProps) {
    useQueryRules(props);

    return null;
  }

  // Query rule custom data
  function CustomQueryRuleCustomData(props: UseQueryRulesProps) {
    const { items } = useQueryRules(props);

    return (
      <>
        {items.map(({ title, link, banner }) => (
          <section key={title}>
            <h2>{title}</h2>
            <a href={link}>
              <img src={banner} alt="" />
            </a>
          </section>
        ))}
      </>
    );
  }
  ```
</CodeGroup>

## Parameters

<ParamField body="trackedFilters" type="Record<string, (facetValues: Array<string  |  number  |  boolean>) => Array<string  |  number  |  boolean>>">
  The filters to track to trigger rule contexts.

  Each filter is a function which name is the attribute you want to track.
  They receive their current refinements as arguments.
  You can either compute the filters you want to track based on those,
  or return static values.
  When the tracked values are refined, it toggles the associated rule contexts.

  The added rule contexts follow the format `ais-{attribute}-{value}` (for example `ais-genre-Thriller`).
  If the context of your rule follows another format,
  you can specify it using the [`transformRuleContexts`](/doc/api-reference/widgets/query-rules/react#param-transform-rule-contexts) option.

  Values are escaped so that they only consist of alphanumeric characters, hyphens, and underscores.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    const trackedFilters = {
      genre: () => ["Comedy", "Thriller"], // this tracks two static genre values
      rating: (values) => values, // this tracks all the rating values
    };

    function QueryRules() {
      const queryRulesApi = useQueryRules({
        trackedFilters,
      });

      return <>{/* Your JSX */}</>;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { UseQueryRulesProps } from "react-instantsearch";

    const trackedFilters: UseQueryRulesProps["trackedFilters"] = {
      genre: () => ["Comedy", "Thriller"], // this tracks two static genre values
      rating: (values) => values, // this tracks all the rating values
    };

    function QueryRules() {
      const queryRulesApi = useQueryRules({
        trackedFilters,
      });

      return <>{/* Your JSX */}</>;
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="transformRuleContexts" type="(ruleContexts: string[]) => string[]">
  A function to apply to the Rule contexts before sending them to Algolia. This is useful to rename Rule contexts that follow a different naming convention.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    const transformRuleContexts = (ruleContexts) => {
      return ruleContexts.map((ruleContext) =>
        ruleContext.replace("ais-", "custom-"),
      );
    };

    function QueryRules() {
      const queryRulesApi = useQueryRules({
        transformRuleContexts,
      });

      return <>{/* Your JSX */}</>;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { UseQueryRulesProps } from "react-instantsearch";

    const transformRuleContexts: UseQueryRulesProps["transformRuleContexts"] = (
      ruleContexts
    ) => {
      return ruleContexts.map((ruleContext) =>
        ruleContext.replace("ais-", "custom-")
      );
    };

    function QueryRules() {
      const queryRulesApi = useQueryRules({
        transformRuleContexts,
      });

      return <>{/* Your JSX */}</>;
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="transformItems" type="(items: object[], metadata: { results: SearchResults }) => object[]">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    // Using only items
    const transformItems = (items) => {
      return items.filter((item) => typeof item.banner !== "undefined");
    };

    // Using items and results
    const transformItems = (items, { results }) => {
      return items.map((item) => ({
        ...item,
        visible: results.page === 0,
      }));
    };

    function QueryRules() {
      const queryRulesApi = useQueryRules({
        transformItems,
      });

      return <>{/* Your JSX */}</>;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { UseQueryRulesProps } from "react-instantsearch";

    // Using only items
    const transformItems: UseQueryRulesProps["transformItems"] = (items) => {
      return items.filter((item) => typeof item.banner !== "undefined");
    };

    // Using items and results
    const transformItems: UseQueryRulesProps["transformItems"] = (
      items,
      { results }
    ) => {
      return items.map((item) => ({
        ...item,
        visible: results.page === 0,
      }));
    };

    function QueryRules() {
      const queryRulesApi = useQueryRules({
        transformItems,
      });

      return <>{/* Your JSX */}</>;
    }
    ```
  </CodeGroup>
</ParamField>

## Returns

<ResponseField name="items" type="any[]">
  The items that matched the rule.

  ```jsx JavaScript icon=code theme={"system"}
  function QueryRuleCustomData(props) {
    const { items } = useQueryRules(props);

    return (
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item.title}</li>
        ))}
      </ul>
    );
  }
  ```
</ResponseField>
