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

---
id: afc597f2-f3bd-460d-9920-c83ea0cf4a61
---

# Hooks

> Reference information for hooks provided by the UI extensions SDK.

Hooks are used to simplify accessing context, performing actions, and fetching CRM data within UI extensions. The hooks provided by the UI extensions SDK are optimized to prevent unnecessary re-renders and automatically clean up resources when components unmount. You can pass inline arrays and objects to the hooks directly, as memoization is not required.

## Universal hooks

> [card]
>
> **Universal hooks**
>
> Supported in all extension points: `crm.record.tab`, `crm.record.sidebar`, `crm.preview`, `helpdesk.sidebar`, `settings`, `home`
>
> | Hook | Description |
> | - | - |
> | [`useExtensionApi`](#useextensionapi) | Access both context and actions from a single hook. |
> | [`useExtensionContext`](#useextensioncontext) | Access contextual information about the extension environment. |
> | [`useExtensionActions`](#useextensionactions) | Access actions that can be performed within HubSpot. |
> | [`useRecordProperties`](#userecordproperties) | Fetch properties from the provided CRM record with optional formatting. |
> | [`useRecordAssociations`](#userecordassociations) | Fetch CRM records of a specific object type associated with the provided record. |
> | [`useRecordSearch`](#userecordsearch) | Search CRM records by query or structured filters. |
> | [`useRecordAggregation`](#userecordaggregation) | Run grouped counts and numeric metrics over CRM records (experimental). |
> | [`useDebounce`](#usedebounce) | Debounce a rapidly-changing value. |
>
> ```jsx wrap theme={null}
> import {
>   useExtensionApi,
>   // OR
>   useExtensionContext,
>   useExtensionActions,
>   useRecordProperties,
>   useRecordAssociations,
>   useRecordSearch,
>   useDebounce
> } from "@hubspot/ui-extensions";
> import { useRecordAggregation } from "@hubspot/ui-extensions/experimental";
> ```

### useExtensionApi

The `useExtensionApi` hook provides access to available actions and contextual information from a single hook, for extension components that need access to both actions and context.

Otherwise, it's best practice to use the more specific `useExtensionActions` or `useExtensionContext`, depending on your use case.

* For a complete list of available context properties, see the [context reference documentation](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/context.md).
* For a complete list of available actions, see the [actions reference documentation](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/actions.md). The actions available depend on the extension point location.

The following example uses the `useExtensionApi` hook to display an alert (action) containing the user's first name (context) when a button is clicked.

> [tab] Basic usage
>
> ```jsx theme={null}
> import { Button, hubspot, useExtensionApi } from '@hubspot/ui-extensions';
>
> hubspot.extend(() => <MyExtension />);
>
> function MyExtension() {
>   const { actions, context } = useExtensionApi();
>
>   return (
>     <Button onClick={() => actions.addAlert({ message: `Hello ${context.user.firstName}!` })}>
>       Click me
>     </Button>
>   );
> }
> ```

> [tab] Typed usage
>
> ```tsx theme={null}
> import { Button, hubspot, useExtensionApi } from '@hubspot/ui-extensions';
>
> hubspot.extend<'crm.record.tab'>(() => <MyExtension />);
>
> function MyExtension() {
>   const { actions, context } = useExtensionApi<'crm.record.tab'>();
>
>   return (
>     <Button onClick={() => actions.addAlert({ message: `Hello ${context.user.firstName}!` })}>
>       Click me
>     </Button>
>   );
> }
> ```

### useExtensionContext

The `useExtensionContext` hook provides access to contextual information about the current extension environment, including location and other relevant data.

For a complete list of available context properties, see the [context reference documentation](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/context.md).

The following example accesses the current extension location and renders it in a `Text` component:

> [tab] Basic usage
>
> ```jsx theme={null}
> import { Text, hubspot, useExtensionContext } from '@hubspot/ui-extensions';
>
> hubspot.extend(() => <MyExtension />);
>
> function MyExtension() {
>   const context = useExtensionContext();
>
>   return (
>     <Text>Current location: {context.location}</Text>
>   );
> }
> ```

> [tab] Typed usage
>
> ```tsx theme={null}
> import { Text, hubspot, useExtensionContext } from '@hubspot/ui-extensions';
>
> hubspot.extend<'crm.record.tab'>(() => <MyExtension />);
>
> function MyExtension() {
>   const context = useExtensionContext<'crm.record.tab'>();
>
>   return (
>     <Text>Current location: {context.location}</Text>
>   );
> }
> ```

### useExtensionActions

The `useExtensionActions` hook provides access to various actions that can be performed within the HubSpot interface. It's a generic hook that can be typed with specific extension point locations for better TypeScript support.

For a complete list of available actions, see the [actions reference documentation](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/actions.md). The actions available depend on the extension point location.

The following example displays an alert when a button is clicked:

> [tab] Basic usage
>
> ```jsx theme={null}
> import { Button, hubspot, useExtensionActions } from '@hubspot/ui-extensions';
>
> hubspot.extend(() => <MyExtension />);
>
> function MyExtension() {
>   const { addAlert } = useExtensionActions();
>
>   return (
>     <Button onClick={() => addAlert({ message: "Action completed!" })}>
>       Click me
>     </Button>
>   );
> }
> ```

> [tab] Typed usage
>
> ```tsx theme={null}
> import { Button, hubspot, useExtensionActions } from '@hubspot/ui-extensions';
>
> hubspot.extend<'crm.record.tab'>(() => <MyExtension />);
>
> function MyExtension() {
>   const { addAlert } = useExtensionActions<'crm.record.tab'>();
>
>   return (
>     <Button onClick={() => addAlert({ message: "Action completed!" })}>
>       Click me
>     </Button>
>   );
> }
> ```

### useRecordProperties

The `useRecordProperties` hook fetches properties from the provided CRM record with optional formatting. It accepts an array of properties to fetch, the record ID/type, and an optional object of formatting options.

This hook was introduced in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI Extensions SDK.

> [tab] Call
>
> ```jsx theme={null}
>   useRecordProperties({
>       properties: ["firstname", "lastname", "email"],
>       recordId: 123,
>       objectType: "contact",
>       format: {
>           propertiesToFormat: "all",
>           date: {
>               format: "MM-DD-YYYY",
>               relative: false,
>           },
>           dateTime: {
>               format: "MM-DD-YYYY hh:mm",
>               relative: false,
>           },
>           currency: {
>               addSymbol: true,
>           },
>       },
>   });
> ```

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   properties: {
>     "firstname": "Joe",
>     "lastname": "Smith",
>     "email": "joe@joebiz.com"
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch properties
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **properties** `object`
>
> An object with key-value pairs of returned properties, as formatted by `formattingOptions`. Properties are returned in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest property values, with formatting applied as specified in the original hook call.

> [tab] Example usage
>
> ```jsx theme={null}
> import { hubspot, Text, Button, useRecordProperties } from "@hubspot/ui-extensions";
>
> const Extension = () => {
>   const { properties, isLoading, error, refetch, isRefetching } =
>     useRecordProperties({
>       // Array of properties to return
>       properties: ["firstname", "lastname", "email"],
>       // The ID of the record to fetch
>       recordId: 1234,
>       // The ID of the object type to fetch
>       objectType: "0-1",
>       // Optional formatting options for returned data
>       format: {
>         propertiesToFormat: "all",
>         date: {
>           format: "MM-DD-YYYY",
>           relative: false,
>         },
>         dateTime: {
>           format: "MM-DD-YYYY hh:mm",
>           relative: false,
>         },
>         currency: {
>           addSymbol: true,
>         },
>       },
>     });
>
>   if (isLoading) {
>     return <Text> Loading properties... </Text>;
>   }
>
>   if (isRefetching) {
>     return <Text> Refetching properties... </Text>;
>   }
>
>   if (error) {
>     return <Text> Error loading properties: {error.message} </Text>;
>   }
>
>   return (
>     <>
>       <Text>
>         The contact is "{properties.firstname} {properties.lastname}" with email
>         "{properties.email}".{" "}
>       </Text>{" "}
>       <Button onClick={refetch} variant="primary">
>         Refetch property data{" "}
>       </Button>{" "}
>     </>
>   );
> };
>
> hubspot.extend(() => <Extension />);  
> ```

### useRecordAssociations

The `useRecordAssociations` hook fetches CRM records of a specific object type associated with the provided record. It accepts an object containing configuration details for the association fetch request.

This hook was introduced in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI Extensions SDK.

> [tab] Call
>
> ```jsx theme={null}
>   useRecordAssociations({
>     fromObjectType: "contact",
>     fromRecordId: 123,
>     toObjectType: "0-1",
>     properties: ["firstname", "lastname", "email", "phone"],
>     pageSize: 25,
>     format: {
>       propertiesToFormat: "all",
>       date: {
>         format: "MM-DD-YYYY",
>         relative: false,
>       },
>       dateTime: {
>         format: "MM-DD-YYYY hh:mm",
>         relative: false,
>       },
>       currency: {
>         addSymbol: true,
>       },
>     },
>   });    
> ```
>
> **fromObjectType** `string` *required*
>
> The object type of the record for which associations are being fetched.
>
> **fromRecordId** `integer`
>
> The ID of the record for which associations are being fetched.
>
> **toObjectType** `String`
>
> The object type ID to fetch associations from (e.g., ‘0-1’ for contacts).
>
> **properties** `Array`
>
> An optional array of properties to fetch from associated records.
>
> **pageSize** `integer`
>
> An optional number of records per page (defaults to 10).
>
> **format** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `propertiesToFormat` properties can be set to `"all"`, or an array of property names to format. Defaults to `"all"`.
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   results: [
>     {
>       "toObjectId": 70284463640,
>       "associationTypes": [
>           {
>               "category": "HUBSPOT_DEFINED",
>               "typeId": 449,
>               "label": ""
>           }
>       ],
>       "properties": {
>           "email": "emailmaria@hubspot.com",
>           "firstname": "Maria",
>           "lastname": "Johnson (Sample Contact)"
>       }
>     }
>   ],
>   pagination: {
>     "hasNextPage": true,
>     "hasPreviousPage": false,
>     "currentPage": 1,
>     "pageSize": 1,
>     "nextPage": () => {}, // function to fetch results for next page
>     "previousPage": () => {}, // function to fetch results for previous page
>     "reset": () => {} // function to reset to page one of results
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch the latest associations data
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **results** `array`
>
> Association details of the returned CRM records. Includes the following fields:
>
> * `toObjectId`: the ID of the CRM record.
> * `associationTypes`: an array of [association type](https://developers.hubspot.com/docs/api-reference/latest/crm/associations/associate-records/guide.md) information.
> * `properties`: an object containing the requested property data, listed in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **pagination** `object`
>
> An object with pagination utilities, including:
>
> * `hasNextPage`: a boolean indicating if more pages are available.
> * `hasPreviousPage`: a boolean indicating if previous pages exist.
> * `currentPage`: the current page number.
> * `pageSize`: the number of items per page.
> * `nextPage()`: the function to go to next page.
> * `previousPage()`: the function to go to previous page.
> * `reset()`: the function to reset to first page.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest associations data, with formatting applied as specified in the original hook call. The current page will be preserved.

> [tab] Example usage
>
> ```jsx theme={null}
>   import { Text, Button, Flex, hubspot, useRecordAssociations } from "@hubspot/ui-extensions";
>
>   const Extension = () => {
>     const { results, error, isLoading, pagination, isRefetching, refetch } =
>       useRecordAssociations({
>         // Object type of base record to fetch associations for
>         fromObjectType: "0-2",
>         // ID of base record to fetch associations for
>         fromRecordId: 123,
>         // Object type for associations
>         toObjectType: "0-1",
>         // Optional properties to fetch from associated objects
>         properties: ["firstname", "lastname", "email", "phone"],
>         // Optional pagination settings
>         pageSize: 25,
>         // Optional formatting configuration (same as useCrmProperties)
>         format: {
>           propertiesToFormat: "all",
>           date: {
>             format: "MM-DD-YYYY",
>             relative: false,
>           },
>           dateTime: {
>             format: "MM-DD-YYYY hh:mm",
>             relative: false,
>           },
>           currency: {
>             addSymbol: true,
>           },
>         },
>       });
>
>     if (isLoading) {
>       return <Text>Loading associations...</Text>;
>     }
>
>     if (isRefetching) {
>       return <Text>Refetching associations...</Text>;
>     }
>
>     if (error) {
>       return <Text>Error loading associations: {error.message}</Text>;
>     }
>
>     return (
>       <Flex direction="column" gap="medium">
>         <Text>Associations (Page {pagination.currentPage})</Text>
>
>         {results.map((association, index) => (
>           <Flex direction="column" key={association.toObjectId}>
>             <Text>
>               Association {index + 1}: Object ID {association.toObjectId}
>             </Text>
>             <Text>
>               Association Types:{" "}
>               {association.associationTypes.map((type) => type.label).join(", ")}
>             </Text>
>             {Object.entries(association.properties).map(([key, value]) => (
>               <Text key={key}>
>                 {key}: {value || "N/A"}
>               </Text>
>             ))}
>           </Flex>
>         ))}
>
>         <Flex direction="row" gap="sm">
>           <Button
>             onClick={pagination.previousPage}
>             disabled={!pagination.hasPreviousPage}
>             variant="secondary"
>           >
>             Previous Page
>           </Button>
>           <Button
>             onClick={pagination.nextPage}
>             disabled={!pagination.hasNextPage}
>             variant="primary"
>           >
>             Next Page
>           </Button>
>           <Button onClick={pagination.reset} variant="secondary">
>             Reset to First Page
>           </Button>
>           <Button onClick={refetch} variant="primary">
>             Fetch Latest Data
>           </Button>
>         </Flex>
>       </Flex>
>     );
>   };
>
>   hubspot.extend(() => <Extension />);
> ```

### useRecordSearch

The `useRecordSearch` hook searches CRM records of a given object type. The search is built using any combination of text query and structured filters, and returns record IDs, property values, and optional associations. Property values are returned unformatted unless the `format` option is provided.

This hook was introduced in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI Extensions SDK.

> [tab] Call
>
> ```jsx expandable theme={null}
>   useRecordSearch({
>     objectType: "contact",
>     properties: ["firstname", "lastname", "email"],
>     query: "john",
>     filterGroups: [
>       {
>         filters: [
>           { propertyName: "createdate", operator: "GT", value: "1704067200000" },
>         ],
>       },
>     ],
>     sorts: [{ propertyName: "createdate", direction: "DESCENDING" }],
>     pageSize: 20,
>     format: {
>       propertiesToFormat: "all",
>       date: {
>         format: "MM-DD-YYYY",
>         relative: false,
>       },
>       dateTime: {
>         format: "MM-DD-YYYY hh:mm",
>         relative: false,
>       },
>       currency: {
>         addSymbol: true,
>       },
>     },
>   });
> ```
>
> **objectType** `string` *required*
>
> The object type to search. Accepts type IDs (`"0-1"`), names (`"contact"`, `"deal"`), or custom object names with a `p_` prefix (`"p_pets"`).
>
> **properties** `array`
>
> An optional array of properties to return for each result.
>
> **query** `string`
>
> An optional free-text search query matched against the object's default searchable properties.
>
> **filterGroups** `array`
>
> An optional array of filter groups. Groups in the array are OR'd together; filters within a single group are AND'd. Each filter includes a `propertyName`, an `operator` (`EQ`, `NEQ`, `LT`, `LTE`, `GT`, `GTE`, `BETWEEN`, `IN`, `NOT_IN`, `HAS_PROPERTY`, `NOT_HAS_PROPERTY`, `CONTAINS_TOKEN`, `NOT_CONTAINS_TOKEN`), and a `value`, `values`, or `highValue` field depending on the operator. See [search the CRM](https://developers.hubspot.com/docs/api-reference/latest/crm/search-the-crm.md#filter-search-results) for more details.
>
> **sorts** `array`
>
> An optional array of sort configurations. Each item requires a `propertyName` and a `direction` (`"ASCENDING"` or `"DESCENDING"`).
>
> **pageSize** `integer`
>
> An optional number of results per page. Default: `10`. Max: `200`.
>
> **format** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `propertiesToFormat` properties can be set to `"all"`, or an array of property names to format. Defaults to `"all"`.
>
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
>
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.
>
> > [!WARNING]
> >
> > **Please note:** formatting is applied based on property type (`date`, `datetime`, `currency`) rather than content. For example, `date` formatting will not apply to a string type property containing a date value.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   results: [
>     {
>       "objectId": 123456,
>       "properties": {
>         "email": "john@example.com",
>         "firstname": "John",
>         "lastname": "Smith"
>       }
>     }
>   ],
>   total: 342,
>   pagination: {
>     "hasNextPage": true,
>     "hasPreviousPage": false,
>     "currentPage": 1,
>     "pageSize": 10,
>     "nextPage": () => {}, // function to fetch results for next page
>     "previousPage": () => {}, // function to fetch results for previous page
>     "reset": () => {} // function to reset to page one of results
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch the latest search results
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **results** `array`
>
> The matching CRM records for the current page. Each item includes:
>
> * `objectId`: the ID of the CRM record.
> * `properties`: an object containing the requested property data, listed in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **total** `number`
>
> The total number of matching records across all pages.
>
> **pagination** `object`
>
> An object with pagination utilities, including:
>
> * `hasNextPage`: a boolean indicating if more pages are available.
> * `hasPreviousPage`: a boolean indicating if previous pages exist.
> * `currentPage`: the current page number.
> * `pageSize`: the number of items per page.
> * `nextPage()`: the function to go to the next page.
> * `previousPage()`: the function to go to the previous page.
> * `reset()`: the function to reset to the first page.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest search results, with formatting applied as specified in the original hook call. The current page will be preserved.

> [tab] Example usage
>
> ```jsx expandable theme={null}
>   import {
>     hubspot,
>     Text,
>     Button,
>     Flex,
>     useRecordSearch
>   } from "@hubspot/ui-extensions";
>
>   const Extension = () => {
>     const { results, total, isLoading, error, pagination, isRefetching, refetch } = useRecordSearch({
>         objectType: 'contact',
>         properties: ['firstname', 'lastname', 'email'],
>         filterGroups: [{
>           filters: [
>             { propertyName: 'lifecyclestage', operator: 'EQ', value: 'lead' }
>           ]
>         }],
>         sorts: [{ propertyName: 'createdate', direction: 'DESCENDING' }],
>         pageSize: 10,
>       });
>
>     if (isLoading) {
>       return <Text>Loading results...</Text>;
>     }
>
>     if (isRefetching) {
>       return <Text>Refetching results...</Text>;
>     }
>
>     if (error) {
>       return <Text>Error loading results: {error.message}</Text>;
>     }
>
>     return (
>       <Flex direction="column" gap="medium">
>         <Text>{total} records found. Displaying page {pagination.currentPage}.</Text>
>
>         {results.map(record => (
>           <Flex direction="column" key={record.objectId}>
>             <Text>
>               {record.properties.firstname} {record.properties.lastname}: {record.properties.email}
>             </Text>
>           </Flex>
>         ))}
>
>         <Flex direction="row" gap="sm">
>           <Button
>             onClick={pagination.previousPage}
>             disabled={!pagination.hasPreviousPage}
>             variant="secondary"
>           >
>             Previous page
>           </Button>
>           <Button
>             onClick={pagination.nextPage}
>             disabled={!pagination.hasNextPage}
>             variant="primary"
>           >
>             Next page
>           </Button>
>           <Button
>             onClick={pagination.reset}
>             variant="secondary"
>           >
>             Reset to first page
>           </Button>
>           <Button
>             onClick={refetch}
>             variant="primary"
>           >
>             Fetch latest data
>           </Button>
>         </Flex>
>       </Flex>
>     );
>   };
>
>   hubspot.extend(() => <Extension />);
> ```

> [tab] Live search
>
> ```jsx theme={null}
>   import { useState } from 'react';
>   import { hubspot, Input, Text, useRecordSearch, useDebounce } from '@hubspot/ui-extensions';
>
>   const Extension = () => {
>     const [query, setQuery] = useState('');
>     // Waits for the user to stop typing before triggering a new search request
>     const debouncedQuery = useDebounce(query);
>
>     const { results, isLoading } = useRecordSearch({
>       objectType: 'contact',
>       properties: ['firstname', 'lastname', 'email'],
>       query: debouncedQuery,
>     });
>
>     return (
>       <>
>         <Input
>           value={query}
>           onInput={setQuery}
>           placeholder="Type to search..."
>           label="Search Contacts"
>           name="searchContacts"
>         />
>         {isLoading && <Text>Loading...</Text>}
>         {results.map(record => (
>           <Text key={record.objectId}>
>             {record.properties.firstname} {record.properties.lastname}
>           </Text>
>         ))}
>       </>
>     );
>   };
>
>   hubspot.extend(() => <Extension />);
> ```

> [tab] Filter by association
>
> ```jsx theme={null}
>   import React from 'react';
>   import { hubspot, Text, useRecordSearch, useExtensionContext } from '@hubspot/ui-extensions';
>
>   const Extension = () => {
>     const { crm } = useExtensionContext();
>
>     const { results, isLoading } = useRecordSearch(
>       {
>         objectType: 'deal',
>         properties: ['dealname', 'amount', 'dealstage'],
>         filterGroups: [
>           {
>             filters: [
>               {
>                 // 'associations.{objectType}' is a pseudo-property that filters by association
>                 propertyName: 'associations.contact',
>                 operator: 'EQ',
>                 value: crm.objectId,
>               },
>             ],
>           },
>         ],
>         format: {
>           propertiesToFormat: 'all',
>           currency: {
>             addSymbol: true,
>           },
>         },
>       }
>     );
>
>     if (isLoading) return <Text>Loading associated deals...</Text>;
>
>     return (
>       <>
>         {results.map((deal) => (
>           <React.Fragment key={deal.objectId}>
>             <Text>{deal.properties.dealname}</Text>
>             <Text>Amount: {deal.properties.amount}</Text>
>             <Text>Stage: {deal.properties.dealstage}</Text>
>           </React.Fragment>
>         ))}
>       </>
>     );
>   };
>
>   hubspot.extend(() => <Extension />);
> ```

### useCrmSearch

The `useCrmSearch` hook searches CRM records of a given object type. The search is built using any combination of text query and structured filters, and returns record IDs, property values, and optional associations. Property values are returned unformatted unless `propertiesToFormat` is set.

> [!WARNING]
>
> **Please note:** this hook is no longer available in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI extensions SDK. Instead, use the newer [`useRecordSearch`](#userecordsearch) hook instead.

> [tab] Call
>
> ```jsx wrap theme={null}
> useCrmSearch(
>   {
>     objectType: "contact",
>     properties: ["firstname", "lastname", "email"],
>     query: "john",
>     filterGroups: [
>       {
>         filters: [
>           { propertyName: "createdate", operator: "GT", value: "1704067200000" }
>         ]
>       }
>     ],
>     sorts: [{ propertyName: "createdate", direction: "DESCENDING" }],
>     pageLength: 20,
>   },
>   {
>     propertiesToFormat: "all",
>     formattingOptions: {
>       date: {
>         format: "MM-DD-YYYY",
>         relative: false,
>       },
>       dateTime: {
>         format: "MM-DD-YYYY hh:mm",
>         relative: false,
>       },
>       currency: {
>         addSymbol: true,
>       },
>     },
>   }
> );
> ```
>
> **config** `object` *required*
>
> Configures the search request with the following parameters:
>
> * `objectType` required: the object type to search. Accepts type IDs (`"0-1"`), names (`"contact"`, `"deal"`), or custom object names with a `p_` prefix (`"p_pets"`).
> * `properties`: an optional array of properties to return for each result.
> * `query`: an optional free-text search query matched against the object's default searchable properties.
> * `filterGroups`: an optional array of filter groups. Groups in the array are OR'd together; filters within a single group are AND'd. Each filter includes a `propertyName`, an `operator` (`EQ`, `NEQ`, `LT`, `LTE`, `GT`, `GTE`, `BETWEEN`, `IN`, `NOT_IN`, `HAS_PROPERTY`, `NOT_HAS_PROPERTY`, `CONTAINS_TOKEN`, `NOT_CONTAINS_TOKEN`), and a `value`, `values`, or `highValue` field depending on the operator. See [search the CRM](https://developers.hubspot.com/docs/api-reference/latest/crm/search-the-crm.md#filter-search-results) for more details.
> * `sorts`: an optional array of sort configurations. Each item requires a `propertyName` and a `direction` (`"ASCENDING"` or `"DESCENDING"`).
> * `pageLength`: an optional number of results per page. Default: `10`. Max: `200`.
>
> **propertiesToFormat** `'all' | array`
>
> Either `'all'` or an array of property names to format. When omitted, property values are returned unformatted.
>
> **formattingOptions** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
>
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.
>
> > [!WARNING]
> >
> > **Please note:** formatting is applied based on property type (`date`, `datetime`, `currency`) rather than content. For example, `date` formatting will not apply to a string type property containing a date value.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   results: [
>     {
>       "objectId": 123456,
>       "properties": {
>         "email": "john@example.com",
>         "firstname": "John",
>         "lastname": "Smith"
>       }
>     }
>   ],
>   total: 342,
>   pagination: {
>     "hasNextPage": true,
>     "hasPreviousPage": false,
>     "currentPage": 1,
>     "pageSize": 10,
>     "nextPage": () => {}, // function to fetch results for next page
>     "previousPage": () => {}, // function to fetch results for previous page
>     "reset": () => {} // function to reset to page one of results
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch the latest search results
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **results** `array`
>
> The matching CRM records for the current page. Each item includes:
>
> * `objectId`: the ID of the CRM record.
> * `properties`: an object containing the requested property data, listed in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **total** `number`
>
> The total number of matching records across all pages.
>
> **pagination** `object`
>
> An object with pagination utilities, including:
>
> * `hasNextPage`: a boolean indicating if more pages are available.
> * `hasPreviousPage`: a boolean indicating if previous pages exist.
> * `currentPage`: the current page number.
> * `pageSize`: the number of items per page.
> * `nextPage()`: the function to go to the next page.
> * `previousPage()`: the function to go to the previous page.
> * `reset()`: the function to reset to the first page.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest search results, with formatting applied as specified in the original hook call. The current page will be preserved.

> [tab] Example usage
>
> ```jsx wrap highlight={10-22} theme={null}
> import {
>   hubspot,
>   Text,
>   Button,
>   Flex,
>   useCrmSearch
> } from "@hubspot/ui-extensions";
>
> const Extension = () => {
>   const { results, total, isLoading, error, pagination, isRefetching, refetch } = useCrmSearch(
>     {
>       objectType: 'contact',
>       properties: ['firstname', 'lastname', 'email'],
>       filterGroups: [{
>         filters: [
>           { propertyName: 'lifecyclestage', operator: 'EQ', value: 'lead' }
>         ]
>       }],
>       sorts: [{ propertyName: 'createdate', direction: 'DESCENDING' }],
>       pageLength: 10,
>     }
>   );
>
>   if (isLoading) {
>     return <Text>Loading results...</Text>;
>   }
>
>   if (isRefetching) {
>     return <Text>Refetching results...</Text>;
>   }
>
>   if (error) {
>     return <Text>Error loading results: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="medium">
>       <Text>{total} records found. Displaying page {pagination.currentPage}.</Text>
>
>       {results.map(record => (
>         <Flex direction="column" key={record.objectId}>
>           <Text>
>             {record.properties.firstname} {record.properties.lastname}: {record.properties.email}
>           </Text>
>         </Flex>
>       ))}
>
>       <Flex direction="row" gap="sm">
>         <Button
>           onClick={pagination.previousPage}
>           disabled={!pagination.hasPreviousPage}
>           variant="secondary"
>         >
>           Previous page
>         </Button>
>         <Button
>           onClick={pagination.nextPage}
>           disabled={!pagination.hasNextPage}
>           variant="primary"
>         >
>           Next page
>         </Button>
>         <Button
>           onClick={pagination.reset}
>           variant="secondary"
>         >
>           Reset to first page
>         </Button>
>         <Button
>           onClick={refetch}
>           variant="primary"
>         >
>           Fetch latest data
>         </Button>
>       </Flex>
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

> [tab] Live search
>
> ```jsx theme={null}
> import { useState } from 'react';
> import { hubspot, Input, Text, useCrmSearch, useDebounce } from '@hubspot/ui-extensions';
>
> const Extension = () => {
>   const [query, setQuery] = useState('');
>   // Waits for the user to stop typing before triggering a new search request
>   const debouncedQuery = useDebounce(query);
>
>   const { results, isLoading } = useCrmSearch({
>     objectType: 'contact',
>     properties: ['firstname', 'lastname', 'email'],
>     query: debouncedQuery,
>   });
>
>   return (
>     <>
>       <Input
>         value={query}
>         onInput={setQuery}
>         placeholder="Type to search..."
>         label="Search Contacts"
>         name="searchContacts"
>       />
>       {isLoading && <Text>Loading...</Text>}
>       {results.map(record => (
>         <Text key={record.objectId}>
>           {record.properties.firstname} {record.properties.lastname}
>         </Text>
>       ))}
>     </>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

> [tab] Filter by association
>
> ```jsx theme={null}
> import React from 'react';
> import { hubspot, Text, useCrmSearch, useExtensionContext } from '@hubspot/ui-extensions';
>
> const Extension = () => {
>   const { crm } = useExtensionContext();
>
>   const { results, isLoading } = useCrmSearch(
>     {
>       objectType: 'deal',
>       properties: ['dealname', 'amount', 'dealstage'],
>       filterGroups: [
>         {
>           filters: [
>             {
>               // 'associations.{objectType}' is a pseudo-property that filters by association
>               propertyName: 'associations.contact',
>               operator: 'EQ',
>               value: crm.objectId,
>             },
>           ],
>         },
>       ],
>     },
>     {
>       propertiesToFormat: 'all',
>       formattingOptions: {
>         currency: {
>           addSymbol: true,
>         },
>       },
>     },
>   );
>
>   if (isLoading) return <Text>Loading associated deals...</Text>;
>
>   return (
>     <>
>       {results.map((deal) => (
>         <React.Fragment key={deal.objectId}>
>           <Text>{deal.properties.dealname}</Text>
>           <Text>Amount: {deal.properties.amount}</Text>
>           <Text>Stage: {deal.properties.dealstage}</Text>
>         </React.Fragment>
>       ))}
>     </>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

### useRecordAggregation (BETA)

The `useRecordAggregation` hook runs grouped counts and numeric metrics over CRM records, optionally across associated objects, and returns one row per group. HubSpot runs the aggregation server-side, so you don't need to fetch every record with `useCrmSearch` and calculate totals in your extension. Use it for summary data like pipeline value by deal stage, revenue by month, or companies that have no deals.

A query starts from a root object (`from`), can join associated objects (`joins`), groups records by one or more properties (`dimensions`), and calculates values for each group (`measures` and `calculatedMeasures`). You can also filter, sort, and limit the results.

> [!WARNING]
>
> **Please note:** `useRecordAggregation` is currently in beta, and is subject to [HubSpot's Developer Terms](https://legal.hubspot.com/developer-terms) and [Developer Beta Terms](https://legal.hubspot.com/developerbetaterms). The hook is still under active development, and its API may change based on testing and feedback.
>
> Import it from `@hubspot/ui-extensions/experimental`, available in `@hubspot/ui-extensions` version `0.18.0` and later. The `labels` and `formattedRows` results, along with the `format` option, require version `1.0.1` or later.

> [tab] Call
>
> ```jsx wrap theme={null}
> useRecordAggregation({
>   from: { objectType: "0-2", alias: "company" },
>   joins: [{ objectType: "0-3", alias: "deal", joinTo: "company" }],
>   dimensions: [{ source: "company", property: "industry" }],
>   measures: [
>     { name: "companies", metric: "DISTINCT_COUNT", field: { source: "company", property: "hs_object_id" } },
>     { name: "deals", metric: "DISTINCT_COUNT", field: { source: "deal", property: "hs_object_id" } },
>     { name: "totalAmount", metric: "SUM", field: { source: "deal", property: "amount" } },
>   ],
>   calculatedMeasures: [
>     { name: "amountPerCompany", left: "totalAmount", operator: "DIVIDE", right: "companies" },
>   ],
>   filterGroups: [
>     {
>       filters: [
>         { source: "company", propertyName: "lifecyclestage", operator: "EQ", value: "customer" },
>       ],
>     },
>   ],
>   sort: { by: "totalAmount", direction: "DESCENDING" },
>   limit: 20,
> });
> ```
>
> **from** `object` *required*
>
> The root object to aggregate:
>
> * `objectType` required: the object type to aggregate. Accepts type IDs (`"0-3"`), names (`"deal"`), or custom object names with a `p_` prefix (`"p_pets"`).
> * `alias`: an optional name for the root object. You can reference it in the `source` field of dimensions, measures, and filters, and in the `joinTo` field of joins. Fields that omit `source` target the root object.
>
> **joins** `array`
>
> An optional array of up to three associated objects to bring into the query. Each join includes:
>
> * `objectType` required: the object type to join. It must be associated with the object it joins to.
> * `alias` required: a name for the joined object, used in `source` fields.
> * `joinTo`: the alias of the object to join to. Must be the root object's `alias` or the `alias` of a join that appears earlier in the array. Defaults to the root object.
> * `on`: the association type to join on, for when more than one association type exists between the two objects. When omitted, HubSpot selects the association automatically. The value is a string in the format `"<categoryId>-<typeId>"`:
>
>   * `categoryId` is `0` for HubSpot-defined association types, `1` for user-defined association labels, or `2` for integrator-defined association types.
>   * `typeId` is the [association type ID](https://developers.hubspot.com/docs/api-reference/latest/crm/associations/associate-records/guide.md#association-type-id-values) for the direction from the `joinTo` object to the joined object. To find the ID of a custom association label, [retrieve the association labels](https://developers.hubspot.com/docs/api-reference/latest/crm/associations/associations-schema/guide.md#retrieve-association-labels) between the two objects.
>
>   For example, `"0-342"` joins companies to deals using the default company to deal association. If the type ID is for the opposite direction, such as `"0-341"` (deal to company) on a join from companies to deals, the join finds no associated records instead of returning an error.
>
> Joins keep every record from the object being joined to, even when it has no associated record. The joined object's values are `null` for those records.
>
> **dimensions** `array` *required*
>
> The properties to group records by, up to 10. Each unique combination of dimension values produces one row. Pass an empty array to aggregate all matching records into a single row. The row is returned even when no records match, with values like a `COUNT` of `0`. Each dimension includes:
>
> * `property` required: the property to group by.
> * `source`: the alias of the object the property belongs to. Defaults to the root object.
> * `as`: the key for this dimension in each row. Defaults to the value of `property`. Set `as` when two objects in the query share a property name.
> * `dateTrunc`: groups a date or datetime property into calendar buckets in the account's time zone. Accepts `DAY`, `WEEK`, `MONTH`, `QUARTER`, or `YEAR`. Each bucket's value is the bucket's start date as a `YYYY-MM-DD` string (e.g., `"2026-08-01"` for August 2026). `WEEK` buckets start on Monday. Records with no value for the property are grouped into a bucket whose value is `null`.
>
> **measures** `array` *required*
>
> The values to calculate for each group. A query needs at least one entry in `measures` (calculated measures alone aren't enough), and can include up to 10 measures and calculated measures combined. Each measure includes:
>
> * `name` required: the key for this measure in each row.
> * `metric` required: the aggregation to perform. Accepts `COUNT`, `SUM`, `AVERAGE`, `MIN`, `MAX`, `DISTINCT_COUNT`, or `MEDIAN`. Without a `field`, `COUNT` counts the root object's records in each group. With a `field`, it counts the records where that property has a value. `DISTINCT_COUNT` returns an exact count of unique values. To count unique records in a query with joins, use `DISTINCT_COUNT` on the object's `hs_object_id`.
> * `field`: the property to aggregate, as an object with a `property` and an optional `source` alias. Required for every metric except `COUNT`.
> * `fixedBy`: an array of dimension keys (each dimension's `as` or `property` value). The measure is calculated across only those dimensions, ignoring the query's other dimensions. For example, in a query grouped by deal stage and owner, a `SUM` of `amount` with `fixedBy: ["dealstage"]` returns each stage's total on every row for that stage. An empty array behaves the same as omitting `fixedBy`.
>
> **calculatedMeasures** `array`
>
> An optional array of values derived from two other measures, such as a ratio. Calculated measures count toward the limit of 10 measures. Each calculated measure includes:
>
> * `name` required: the key for this value in each row.
> * `left` required and `right` required: the `name` of a measure or another calculated measure. Operands can't reference dimensions or constant numbers, and calculated measures can't reference themselves directly or indirectly. An operand that references a measure with `fixedBy` uses that measure's regular grouped value, not its fixed value.
> * `operator` required: the arithmetic to apply to `left` and `right`. Accepts `ADD`, `SUBTRACT`, `MULTIPLY`, or `DIVIDE`.
>
> **filterGroups** `array`
>
> An optional array of filter groups. Groups in the array are OR'd together; filters within a single group are AND'd. Each filter includes:
>
> * `propertyName` required: the property to filter on.
> * `operator` required: the comparison to make. Accepts `EQ`, `NEQ`, `GT`, `GTE`, `LT`, `LTE`, `IN`, `NOT_IN`, `CONTAINS`, `NOT_CONTAINS`, `STARTS_WITH`, `ENDS_WITH`, `IS_KNOWN`, or `IS_UNKNOWN`.
> * `value`: the value to compare against, as a string. Used by every operator except `IN`, `NOT_IN`, `IS_KNOWN`, and `IS_UNKNOWN`.
> * `values`: a non-empty array of string values, for the `IN` and `NOT_IN` operators.
> * `source`: the alias of the object the property belongs to. Defaults to the root object.
>
> The `GT`, `GTE`, `LT`, and `LTE` operators compare numeric values. To filter a date or datetime property, pass a millisecond timestamp as a string (e.g., `String(date.getTime())`). To find root records with no associated record of a joined type, filter the joined object's `hs_object_id` with `IS_UNKNOWN`.
>
> **sort** `object`
>
> Orders the rows:
>
> * `by` required: the key of a dimension, measure, or calculated measure.
> * `direction`: `"ASCENDING"` or `"DESCENDING"`. Default: `"ASCENDING"`.
>
> Rows with the same `by` value are then ordered by their dimension values in ascending order. Without `sort`, rows are ordered by their dimension values only.
>
> **limit** `number`
>
> The maximum number of rows to return, as a positive integer. Requires `sort`, so the rows returned are always the top results for that sort. Default: `100`. Max: `1000`. Larger values are treated as `1000`.
>
> The hook accepts an optional second argument for display formatting:
>
> ```jsx wrap theme={null}
> useRecordAggregation(config, {
>   format: {
>     propertiesToFormat: ["dealstage", "totalAmount"],
>     currency: { addSymbol: true },
>   },
> });
> ```
>
> **format** `object`
>
> Formats values for display and returns them in `formattedRows`. `rows` stays unchanged. Without `format`, or when `propertiesToFormat` selects nothing, `formattedRows` is `undefined`.
>
> * `propertiesToFormat`: `"all"`, or an array of row keys to format (each dimension's `as` or `property` value, and each measure or calculated measure `name`).
>
> * `currency`: set `addSymbol` to `true` to show a currency symbol. The symbol is shown for properties stored in the [account's company currency](https://knowledge.hubspot.com/account-management/add-and-edit-your-account-currencies), such as `amount_in_home_currency`, or when the query also groups by the record's currency property (e.g., `deal_currency_code`). For a measure with `fixedBy`, the currency property's dimension must be one of its `fixedBy` keys. Other currency values, and values with an invalid currency code, are formatted as plain numbers.
>
> * `date`: set `format` to a date format string for `DAY` and `WEEK` buckets and date values. `MONTH`, `QUARTER`, and `YEAR` buckets use localized formats, such as "Aug 2026" and "Q3 2026". The `relative` option doesn't apply to date buckets.
>
> * `dateTime`: formatting for datetime values, using the same subfields as `date`.
>
> > [!TIP]
> >
> > Rows are typed from the configuration you pass: each row has a key for every dimension's `as` or `property` value, every measure `name`, and every calculated measure `name`. If you define the configuration in a separate variable instead of inline, declare it `as const`. Without it, TypeScript widens values like `metric: "COUNT"` to `string`, and the call doesn't compile.
> >
> > `formattedRows` is typed from the `format` option when you pass it inline: keys selected by `propertiesToFormat` (`"all"`, or an array of keys) are typed as `string | null`, and other keys keep their `rows` type. If you pass the options in a separate variable, every key keeps its `rows` type. Don't declare the options `as const`, because `propertiesToFormat` doesn't accept a read-only array.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   rows: [
>     { industry: "COMPUTER_SOFTWARE", companies: 12, deals: 30, totalAmount: 450000, amountPerCompany: 37500 },
>     { industry: "MARKETING_AND_ADVERTISING", companies: 8, deals: 11, totalAmount: 96000, amountPerCompany: 12000 }
>   ],
>   labels: {
>     industry: { COMPUTER_SOFTWARE: "Computer Software", MARKETING_AND_ADVERTISING: "Marketing and Advertising" }
>   },
>   formattedRows: undefined, // set when the format option is passed
>   truncated: false,
>   isStale: false,
>   dataAge: Date // when the underlying data was last refreshed
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the query is running. Queries can take several seconds.
>
> **error** `object`
>
> For failed queries, an `Error` with a `message` and a `code`. The `code` is `TIMEOUT` when the hook stops waiting for results after 45 seconds, or `FAILED` for any other failure, such as an invalid configuration, a query over the limits, missing permissions, or a query that times out on HubSpot's side. Will be `null` for successful queries.
>
> **rows** `array`
>
> One object per group. Each row includes a key for every dimension, measure, and calculated measure in the query:
>
> * Values from numeric aggregations, such as `COUNT` and `SUM`, are numbers.
> * Dimension values are the values stored in HubSpot's reporting data, such as a deal stage's internal ID rather than its label. To display them, use `labels`. Free-text values, such as a company `name`, can be returned in lowercase. Date buckets from `dateTrunc` are `YYYY-MM-DD` strings.
> * A value is `null` when there's no data for it, such as a joined object's property on a record with no associated record.
>
> Group, filter, sort, and compare on `rows`, so that two records with the same label (such as two owners with the same name) stay separate.
>
> **labels** `object`
>
> Display labels for dropdown-style dimensions, such as deal stages, pipelines, owners, and other enumeration properties. Keyed by dimension (its `as` or `property` value), then by the value in `rows`: `labels[dimension][value]`. Labels are included automatically, and pass directly to a chart's `propertyLabels` option. Pipeline stage labels include the pipeline's name, such as `Closed Won (Sales Pipeline)`.
>
> `labels` only includes values that appear in `rows` and have a label that's different from the value. When a value has no entry, display the value itself. Date buckets and free-text properties aren't labeled. Will be `{}` when no dimension has labels, or when labels are temporarily unavailable.
>
> **formattedRows** `array | undefined`
>
> The same rows as `rows`, in the same order and with the same keys, with the keys selected by `format.propertiesToFormat` converted to display strings. Labeled dimensions use their label, date buckets are formatted as dates (e.g., "Aug 2026"), and numbers are formatted for the user's locale. Keys that aren't selected keep their original values, and `null` values stay `null`. Will be `undefined` without the `format` option or while loading. If formatting fails, such as when property definitions can't be loaded, the hook returns an `error` instead of unformatted results. Use `formattedRows` for tables and statistics, and `rows` for charts, which need numeric values.
>
> **truncated** `boolean`
>
> `true` when more groups matched the query than were returned, because of the `limit` or the default of 100 rows. Treat a truncated result as the top rows for your `sort` rather than a complete set.
>
> **isStale** `boolean`
>
> `true` when the results come from an older cached copy of the reporting data.
>
> **dataAge** `Date | null`
>
> When the underlying reporting data was last refreshed. Use it to show when the data is from, like "Data as of 10:42 AM". Will be `null` when the information isn't available.
>
> Unlike `useCrmSearch`, the hook doesn't return a `total`, `pagination`, or a `refetch` function.

> [tab] Example usage
>
> The following example shows each deal stage with its number of deals and total amount, ordered by total amount. Each stage is displayed by its label from `labels`, falling back to the stage's internal value:
>
> ```jsx wrap highlight={5-13} theme={null}
> import { Flex, Text, hubspot } from "@hubspot/ui-extensions";
> import { useRecordAggregation } from "@hubspot/ui-extensions/experimental";
>
> const Extension = () => {
>   const { rows, labels, isLoading, error, truncated, dataAge } = useRecordAggregation({
>     from: { objectType: "0-3" },
>     dimensions: [{ property: "dealstage" }],
>     measures: [
>       { name: "deals", metric: "COUNT" },
>       { name: "totalAmount", metric: "SUM", field: { property: "amount" } },
>     ],
>     sort: { by: "totalAmount", direction: "DESCENDING" },
>   });
>
>   if (isLoading) {
>     return <Text>Loading pipeline...</Text>;
>   }
>
>   if (error) {
>     return <Text>Couldn't load pipeline: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="small">
>       {rows.map((row) => (
>         <Text key={String(row.dealstage)}>
>           {labels.dealstage?.[String(row.dealstage)] ?? row.dealstage}: {row.deals} deals, ${Number(row.totalAmount ?? 0).toLocaleString()}
>         </Text>
>       ))}
>       {truncated && <Text variant="microcopy">Showing the top {rows.length} stages.</Text>}
>       {dataAge && <Text variant="microcopy">Data as of {dataAge.toLocaleString()}</Text>}
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

> [tab] Monthly trend
>
> The following example uses `dateTrunc` to total closed won deal amounts by month, for deals with a close date on or after the first day of the month six months ago. The start date is rounded to the first day of the month, so the filter value doesn't change between renders. The `format` option returns each month (e.g., "Aug 2026") and total (e.g., "\$45,000.00") as display strings in `formattedRows`. The total uses `amount_in_home_currency`, which is stored in the account's company currency, so it can show a currency symbol:
>
> ```jsx wrap highlight={10-28} theme={null}
> import { Flex, Text, hubspot } from "@hubspot/ui-extensions";
> import { useRecordAggregation } from "@hubspot/ui-extensions/experimental";
>
> const Extension = () => {
>   // The first day of the month, six months ago
>   const start = new Date();
>   start.setMonth(start.getMonth() - 6, 1);
>   start.setHours(0, 0, 0, 0);
>
>   const { formattedRows, isLoading, error } = useRecordAggregation({
>     from: { objectType: "0-3" },
>     filterGroups: [
>       {
>         filters: [
>           { propertyName: "dealstage", operator: "EQ", value: "closedwon" },
>           // Date filters take millisecond timestamps as strings
>           { propertyName: "closedate", operator: "GTE", value: String(start.getTime()) },
>         ],
>       },
>     ],
>     dimensions: [{ property: "closedate", as: "month", dateTrunc: "MONTH" }],
>     measures: [
>       { name: "revenue", metric: "SUM", field: { property: "amount_in_home_currency" } },
>     ],
>     sort: { by: "month", direction: "ASCENDING" },
>   }, {
>     format: { propertiesToFormat: ["month", "revenue"], currency: { addSymbol: true } },
>   });
>
>   if (isLoading) {
>     return <Text>Loading revenue...</Text>;
>   }
>
>   if (error) {
>     return <Text>Couldn't load revenue: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="small">
>       {(formattedRows ?? []).map((row) => (
>         <Text key={String(row.month)}>
>           {row.month}: {row.revenue ?? "No revenue"}
>         </Text>
>       ))}
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

> [tab] Chart
>
> The following example charts report on total deal amount by deal stage. The `labels` object is passed directly to the chart's `propertyLabels` option, so the x-axis shows stage labels while the chart data keeps each stage's internal value. Charts need numeric values, so the example builds its data from `rows` and replaces `null` values:
>
> ```jsx wrap highlight={5-12} theme={null}
> import { BarChart, Text, hubspot } from "@hubspot/ui-extensions";
> import { useRecordAggregation } from "@hubspot/ui-extensions/experimental";
>
> const Extension = () => {
>   const { rows, labels, isLoading, error } = useRecordAggregation({
>     from: { objectType: "0-3" },
>     dimensions: [{ property: "dealstage" }],
>     measures: [
>       { name: "totalAmount", metric: "SUM", field: { property: "amount_in_home_currency" } },
>     ],
>     sort: { by: "totalAmount", direction: "DESCENDING" },
>   });
>
>   const chartData = rows.map((row) => ({
>     dealstage: String(row.dealstage ?? "None"),
>     totalAmount: Number(row.totalAmount ?? 0),
>   }));
>
>   if (isLoading) {
>     return <Text>Loading pipeline...</Text>;
>   }
>
>   if (error) {
>     return <Text>Couldn't load pipeline: {error.message}</Text>;
>   }
>
>   return (
>     <BarChart
>       data={{ data: chartData, options: { propertyLabels: labels } }}
>       axes={{
>         x: { field: "dealstage", fieldType: "category", label: "Deal stage" },
>         y: { field: "totalAmount", fieldType: "linear", label: "Total amount" },
>       }}
>     />
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

> [tab] Joined objects
>
> The following example joins deals to companies and filters the joined deal's `hs_object_id` with `IS_UNKNOWN`, which returns only companies that have no associated deals. Grouping by the company's `hs_object_id` as well as its `name` keeps companies that share a name in separate rows:
>
> ```jsx wrap highlight={5-22} theme={null}
> import { Flex, Text, hubspot } from "@hubspot/ui-extensions";
> import { useRecordAggregation } from "@hubspot/ui-extensions/experimental";
>
> const Extension = () => {
>   const { rows, isLoading, error, truncated } = useRecordAggregation({
>     from: { objectType: "0-2", alias: "company" },
>     joins: [{ objectType: "0-3", alias: "deal", joinTo: "company" }],
>     dimensions: [
>       { source: "company", property: "name" },
>       { source: "company", property: "hs_object_id", as: "companyId" },
>     ],
>     measures: [{ name: "companies", metric: "COUNT" }],
>     filterGroups: [
>       {
>         filters: [
>           { source: "deal", propertyName: "hs_object_id", operator: "IS_UNKNOWN" },
>         ],
>       },
>     ],
>     sort: { by: "name", direction: "ASCENDING" },
>     limit: 50,
>   });
>
>   if (isLoading) {
>     return <Text>Finding companies without deals...</Text>;
>   }
>
>   if (error) {
>     return <Text>Couldn't load companies: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="small">
>       <Text format={{ fontWeight: "bold" }}>
>         {truncated ? `First ${rows.length}` : rows.length} companies with no deals
>       </Text>
>       {rows.map((row) => (
>         <Text key={String(row.companyId)}>{row.name}</Text>
>       ))}
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

> [tab] Calculated measures
>
> The following example divides each deal stage's total amount by its number of deals to show the average deal size per stage:
>
> ```jsx wrap highlight={5-16} theme={null}
> import { Flex, Text, hubspot } from "@hubspot/ui-extensions";
> import { useRecordAggregation } from "@hubspot/ui-extensions/experimental";
>
> const Extension = () => {
>   const { rows, isLoading, error } = useRecordAggregation({
>     from: { objectType: "0-3" },
>     dimensions: [{ property: "dealstage" }],
>     measures: [
>       { name: "deals", metric: "COUNT" },
>       { name: "totalAmount", metric: "SUM", field: { property: "amount" } },
>     ],
>     calculatedMeasures: [
>       { name: "averageAmount", left: "totalAmount", operator: "DIVIDE", right: "deals" },
>     ],
>     sort: { by: "averageAmount", direction: "DESCENDING" },
>   });
>
>   if (isLoading) {
>     return <Text>Loading deal sizes...</Text>;
>   }
>
>   if (error) {
>     return <Text>Couldn't load deal sizes: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="small">
>       {rows.map((row) => (
>         <Text key={String(row.dealstage)}>
>           {row.dealstage}: ${Math.round(Number(row.averageAmount ?? 0)).toLocaleString()} average across {row.deals} deals
>         </Text>
>       ))}
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

When using `useRecordAggregation`, keep the following in mind:

* **Query limits:** a query can include up to three joins, 10 dimensions, and 10 measures (including calculated measures). A query over these limits returns a `FAILED` error.
* **Truncated results:** results are capped rather than paginated. When `truncated` is `true`, raise the `limit` (up to 1,000), narrow your filters, or group by a broader dimension (e.g., `MONTH` instead of `DAY`).
* **Timeouts:** the hook waits up to 45 seconds for a query to complete, then returns a `TIMEOUT` error. A query that times out on HubSpot's side returns a `FAILED` error.
* **Data freshness:** results can come from a cache, so they may not reflect the latest changes to CRM data. Use `dataAge` to show when the data was last refreshed, and `isStale` to flag older results. The hook has no refetch function. It runs a new query when its configuration changes or the component remounts, and a new query can still return cached results.
* **Stable configuration:** because the hook runs a new query whenever its configuration changes, avoid values that change on every render, such as `Date.now()`. Round dates to a fixed boundary, like the start of a day or month, instead. Changing the configuration also clears the current `rows` and sets `isLoading` to `true` until the new results arrive.
* **Labels:** the `labels` property covers only the values returned in `rows`. It isn't a complete list of a property's options and doesn't define their order (such as pipeline stage order). For a complete list of options, such as for a filter dropdown, [retrieve the property](https://developers.hubspot.com/docs/api-reference/latest/crm/properties/guide.md#retrieve-properties) and read its `options`. For stage order, [retrieve the pipeline's stages](https://developers.hubspot.com/docs/api-reference/latest/crm/pipelines/guide.md#retrieve-stages) and sort them by `displayOrder`. Extensions call these APIs from a backend, either your own through [`hubspot.fetch()`](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/fetching-data#hubspot-fetch) or a [serverless function](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/fetching-data.md#serverless-functions).
* **Raw values for logic:** use `rows` for grouping, filtering, and comparisons, and `labels` or `formattedRows` only for display. Labels aren't unique, so two owners with the same name have different values in `rows` but share the same label.
* **Permissions:** your app needs read [scopes](https://developers.hubspot.com/docs/apps/developer-platform/build-apps/authentication/scopes.md) for the root object and every joined object. If a dimension, measure, or filter uses a [sensitive data](https://developers.hubspot.com/docs/api-reference/latest/crm/properties/sensitive-data.md) property and your app doesn't have the matching sensitive data scope, the whole query fails. Results also respect the viewing user's record and property permissions.

### useDebounce

The `useDebounce` hook prevents a rapidly-changing value from propagating until it has stopped changing for a given number of milliseconds. Use it to avoid triggering expensive operations (like [CRM search API](https://developers.hubspot.com/docs/api-reference/latest/crm/search-the-crm.md) requests) on every change, and instead wait until the user has paused.

```jsx wrap theme={null}
import { useDebounce } from '@hubspot/ui-extensions';

const [searchText, setSearchText] = useState('');
// debouncedQuery only updates after searchText has been stable for 300ms
const debouncedQuery = useDebounce(searchText, 300);
```

The hook accepts any JSON-serializable value: strings, numbers, booleans, `null`, arrays, and objects. Objects and arrays are compared by deep equality, so a new object reference with the same content won't reset the debounce timer. Passing a non-serializable value (e.g., a function or a `Date` object) will result in incorrect deep equality comparisons.

```jsx wrap theme={null}
const [filters, setFilters] = useState({ status: 'OPEN', assignee: null });
const debouncedFilters = useDebounce(filters, 500);
```

| Parameter | Type | Description |
| - | - | - |
| `value` required | `string` \| `number` \| `boolean` \| `null` \| `object` \| `array` | The value to debounce. Must be JSON-serializable. Objects and arrays are compared by deep equality, so a new object reference with the same content won't reset the debounce timer. Functions and class instances are not supported. |
| `delayMs` | `number` | Milliseconds to wait after the last change before updating the debounced value. Defaults to `300`. Changing this value mid-render resets the pending timer. Passing a value of `0` still defers the update by one render cycle because the underlying `useEffect` is asynchronous. |

The hook returns the debounced version of `value` with the same type as the input. On the initial render, `value` is returned immediately without delay. The pending timer is cancelled when the component unmounts.

> [tab] Debouncing a search input
>
> Pair `useDebounce` with `useCrmSearch` (or any data-fetching hook) to avoid firing a request on every keystroke:
>
> ```jsx theme={null}
> import { useState } from 'react';
> import { Input, Text, useDebounce, useCrmSearch, hubspot } from '@hubspot/ui-extensions';
>
> const Extension = () => {
>   const [query, setQuery] = useState('');
>   const debouncedQuery = useDebounce(query, 300);
>
>   const { results, isLoading } = useCrmSearch({
>     objectType: '0-1',
>     query: debouncedQuery,
>     properties: ['firstname', 'lastname', 'email'],
>   });
>
>   return (
>     <>
>       <Input
>         label="Search contacts"
>         name="search-contacts"
>         onInput={setQuery}
>       />
>       {isLoading && <Text>Searching...</Text>}
>       {results.map((r) => (
>         <Text key={r.objectId}>
>           {r.properties.firstname} {r.properties.lastname}
>         </Text>
>       ))}
>     </>
>   );
> };
>
> hubspot.extend(() => <Extension />);
>
> ```

> [tab] Showing validation after pause
>
> Debounce validation to avoid showing an error message on every keystroke and instead waiting until the user has finished typing. In this example, the error only appears after the user pauses for 400ms.
>
> ```jsx theme={null}
> import { useState } from 'react';
> import { Input, Alert, useDebounce, hubspot } from '@hubspot/ui-extensions';
>
> const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
>
> const Extension = () => {
>   const [email, setEmail] = useState('');
>   const debouncedEmail = useDebounce(email, 400);
>
>   const isInvalid =
>     debouncedEmail.length > 0 && !EMAIL_PATTERN.test(debouncedEmail);
>
>   return (
>     <>
>       <Input label="Email address" name="email-address" onInput={setEmail} />
>       {isInvalid && (
>         <Alert variant="danger" title="Invalid email address">
>           Don't forget to add a valid email address!
>         </Alert>
>       )}
>     </>
>   );
> };
>
> hubspot.extend(() => <Extension />);
>
> ```

## CRM-specific hooks

These hooks are only available in CRM extension points (`crm.record.tab`, `crm.record.sidebar`, `crm.preview`, and `helpdesk.sidebar`). Ensure you're on the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI extensions SDK to use these hooks in your app:

* [`useRecordPropertiesCurrent`](#useRecordPropertiesCurrent): fetch properties from the current CRM record.
* [`useRecordAssociationsCurrent`](#userecordassociationscurrent): fetch records associated with the current CRM record.

> [!WARNING]
>
> Note that the [`useCrmProperties`](#usecrmproperties) and [`useAssociations`](#useassociations) hooks are no longer available in the latest version (`v1`) of the UI extensions SDK, and have been replaced with the newer [`useRecordPropertiesCurrent`](#useRecordPropertiesCurrent) and [`useRecordAssociationsCurrent`](#userecordassociationscurrent) hooks respectively.

**Example import usage:**

```jsx wrap theme={null}
import {
  useRecordPropertiesCurrent,
  useRecordAssociationsCurrent
} from "@hubspot/ui-extensions/crm";
```

### useRecordPropertiesCurrent

> [!NOTE]
>
> As of version `v1` of the UI extensions SDK, the `useRecordPropertiesCurrent` hook has replaced the older `useCrmProperties` hook. Learn more in the [UI extensions SDK versioning guide](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md).

The `useRecordPropertiesCurrent` hook fetches properties from the current CRM record with optional formatting. It accepts an object that includes an array of properties to fetch, along with an optional object to format the returned data.

> [tab] Call
>
> ```jsx theme={null}
> useRecordPropertiesCurrent({
>     properties: ["firstname", "lastname", "email"],
>     format: {
>         propertiesToFormat: "all",
>         date: {
>             format: "MM-DD-YYYY",
>             relative: false,
>         },
>         dateTime: {
>             format: "MM-DD-YYYY hh:mm",
>             relative: false,
>         },
>         currency: {
>             addSymbol: true,
>         },
>     },
> });
> ```
>
> **properties** `array` *required*
>
> An array of property names to fetch.
>
> **format** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `propertiesToFormat` properties can be set to `"all"`, or an array of property names to format. Defaults to `"all"`.
>
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
>
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.
>
> > [!WARNING]
> >
> > Formatting is applied based on property type (`date`, `datetime`, `currency`) rather than content. For example, `date` formatting will not apply to a string type property containing a date value.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   properties: {
>     "firstname": "Joe",
>     "lastname": "Smith",
>     "email": "joe@joebiz.com"
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch properties
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **properties** `object`
>
> An object with key-value pairs of returned properties, as formatted by `formattingOptions`. Properties are returned in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest property values, with formatting applied as specified in the original hook call.

> [tab] Example usage
>
> ```jsx theme={null}
> import { hubspot, Text, Button } from "@hubspot/ui-extensions";
> import { useRecordPropertiesCurrent } from "@hubspot/ui-extensions/crm";
>
> const Extension = () => {
>   const { properties, isLoading, error, refetch, isRefetching } =
>     useRecordPropertiesCurrent({
>       // Array of properties to return
>       properties: ["firstname", "lastname", "email"],
>       // Optional formatting options for returned data
>       format: {
>         propertiesToFormat: "all",
>         date: {
>           format: "MM-DD-YYYY",
>           relative: false,
>         },
>         dateTime: {
>           format: "MM-DD-YYYY hh:mm",
>           relative: false,
>         },
>         currency: {
>           addSymbol: true,
>         },
>       },
>     });
>
>   if (isLoading) {
>     return <Text> Loading properties... </Text>;
>   }
>
>   if (isRefetching) {
>     return <Text> Refetching properties... </Text>;
>   }
>
>   if (error) {
>     return <Text> Error loading properties: {error.message} </Text>;
>   }
>
>   return (
>     <>
>       <Text>
>         The contact is "{properties.firstname} {properties.lastname}" with email
>         "{properties.email}".{" "}
>       </Text>{" "}
>       <Button onClick={refetch} variant="primary">
>         Refetch property data{" "}
>       </Button>{" "}
>     </>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

### useCrmProperties

> [!WARNING]
>
> **Please note:** this hook is no longer available in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI extensions SDK. Instead, use the newer [`useRecordPropertiesCurrent`](#userecordpropertiescurrent) hook instead.

The `useCrmProperties` hook fetches properties from the current CRM record with optional formatting. It accepts an array of properties to fetch, along with an optional object to format the returned data.

> [tab] Call
>
> ```jsx theme={null}
> useCrmProperties(["firstname", "lastname", "email"], {
>   propertiesToFormat: "all",
>   formattingOptions: {
>     date: {
>       format: "MM-DD-YYYY",
>       relative: false,
>     },
>     dateTime: {
>       format: "MM-DD-YYYY hh:mm",
>       relative: false,
>     },
>     currency: {
>       addSymbol: true,
>     },
>   },
> });
> ```
>
> **propertiesToFormat** `'all' | array` *required*
>
> Either `'all'` or an array of property names to format.
>
> **formattingOptions** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
>
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.
>
> > [!WARNING]
> >
> > Formatting is applied based on property type (`date`, `datetime`, `currency`) rather than content. For example, `date` formatting will not apply to a string type property containing a date value.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   properties: {
>     "firstname": "Joe",
>     "lastname": "Smith",
>     "email": "joe@joebiz.com"
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch properties
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **properties** `object`
>
> An object with key-value pairs of returned properties, as formatted by `formattingOptions`. Properties are returned in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest property values, with formatting applied as specified in the original hook call.

> [tab] Example usage
>
> ```jsx highlight={8-26} theme={null}
> import {
>   hubspot,
>   Text,
>   Button
> } from "@hubspot/ui-extensions";
> import { useCrmProperties } from "@hubspot/ui-extensions/crm";
>
> const Extension = () => {
>   const { properties, isLoading, error, refetch, isRefetching } = useCrmProperties(
>     // Array of properties to return
>     ['firstname', 'lastname', 'email'],
>     // Optional formatting options for returned data
>     {
>       propertiesToFormat: 'all',
>       formattingOptions: {
>         date: {
>           format: 'MM-DD-YYYY',
>           relative: false
>         },
>         dateTime: {
>           format: 'MM-DD-YYYY hh:mm',
>           relative: false
>         },
>         currency: {
>           addSymbol: true
>         }
>       }
>     }
>   );
>
>   if (isLoading) {
>     return <Text>Loading properties...</Text>;
>   }
>
>   if (isRefetching) {
>     return <Text>Refetching properties...</Text>;
>   }
>
>   if (error) {
>     return <Text>Error loading properties: {error.message}</Text>;
>   }
>   return (
>     <>
>       <Text>
>         The contact is "{properties.firstname} {properties.lastname}"
>         with email "{properties.email}".
>       </Text>
>       <Button onClick={refetch} variant="primary">
>         Refetch property data
>       </Button>
>     </>
>   );
> };
> hubspot.extend(() => <Extension />);
> ```

### useRecordAssociationsCurrent

The `useRecordAssociationsCurrent` hook fetches CRM records of a specific object type associated with the currently displaying record.  It accepts an object containing the object type ID of the associated record, the properties to fetch from the associated object, an optional number of associated records to retrieve, and an optional object that formats returned property data.

This hook was introduced in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI Extensions SDK.

> [tab] Call
>
> ```jsx theme={null}
>   useRecordAssociationsCurrent({
>     toObjectType: "0-1",
>     properties: ["firstname", "lastname", "email", "phone"],
>     pageSize: 25,
>     format: {
>       propertiesToFormat: "all",
>       date: {
>         format: "MM-DD-YYYY",
>         relative: false,
>       },
>       dateTime: {
>         format: "MM-DD-YYYY hh:mm",
>         relative: false,
>       },
>       currency: {
>         addSymbol: true,
>       },
>     },
>   });
> ```
>
> **toObjectType** `string` *required*
>
> The object type ID to fetch associations from (e.g., '0-1' for contacts).
>
> * `properties`:
> * `pageLength`: an optional number of items per page (defaults to 10).
>
> **properties** `'all' | array`
>
> An optional array of properties to fetch from associated records.
>
> **pageSize** `integer`
>
> An optional number of records per page (defaults to 10).
>
> **format** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `propertiesToFormat` properties can be set to `"all"`, or an array of property names to format. Defaults to `"all"`.
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   results: [
>     {
>       "toObjectId": 70284463640,
>       "associationTypes": [
>           {
>               "category": "HUBSPOT_DEFINED",
>               "typeId": 449,
>               "label": ""
>           }
>       ],
>       "properties": {
>           "email": "emailmaria@hubspot.com",
>           "firstname": "Maria",
>           "lastname": "Johnson (Sample Contact)"
>       }
>     }
>   ],
>   pagination: {
>     "hasNextPage": true,
>     "hasPreviousPage": false,
>     "currentPage": 1,
>     "pageSize": 1,
>     "nextPage": () => {}, // function to fetch results for next page
>     "previousPage": () => {}, // function to fetch results for previous page
>     "reset": () => {} // function to reset to page one of results
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch the latest associations data
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **results** `array`
>
> Association details of the returned CRM records. Includes the following fields:
>
> * `toObjectId`: the ID of the CRM record.
> * `associationTypes`: an array of [association type](https://developers.hubspot.com/docs/api-reference/latest/crm/associations/associate-records/guide.md) information.
> * `properties`: an object containing the requested property data, listed in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **pagination** `object`
>
> An object with pagination utilities, including:
>
> * `hasNextPage`: a boolean indicating if more pages are available.
> * `hasPreviousPage`: a boolean indicating if previous pages exist.
> * `currentPage`: the current page number.
> * `pageSize`: the number of items per page.
> * `nextPage()`: the function to go to next page.
> * `previousPage()`: the function to go to previous page.
> * `reset()`: the function to reset to first page.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest associations data, with formatting applied as specified in the original hook call. The current page will be preserved.

> [tab] Example usage
>
> ```jsx theme={null}
> import { Text, Button, Flex, hubspot } from "@hubspot/ui-extensions";
> import { useRecordAssociationsCurrent } from "@hubspot/ui-extensions/crm";
>
> const Extension = () => {
>   const { results, error, isLoading, pagination, isRefetching, refetch } =
>     useRecordAssociationsCurrent({
>       // Object type ID to fetch associations for
>       toObjectType: "0-1",
>       // Optional properties to fetch from associated objects
>       properties: ["firstname", "lastname", "email", "phone"],
>       // Optional pagination settings
>       pageSize: 25,
>       // Optional formatting configuration (same as useCrmProperties)
>       format: {
>         propertiesToFormat: "all",
>         date: {
>           format: "MM-DD-YYYY",
>           relative: false,
>         },
>         dateTime: {
>           format: "MM-DD-YYYY hh:mm",
>           relative: false,
>         },
>         currency: {
>           addSymbol: true,
>         },
>       },
>     });
>
>   if (isLoading) {
>     return <Text>Loading associations...</Text>;
>   }
>
>   if (isRefetching) {
>     return <Text>Refetching associations...</Text>;
>   }
>
>   if (error) {
>     return <Text>Error loading associations: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="medium">
>       <Text>Associations (Page {pagination.currentPage})</Text>
>
>       {results.map((association, index) => (
>         <Flex direction="column" key={association.toObjectId}>
>           <Text>
>             Association {index + 1}: Object ID {association.toObjectId}
>           </Text>
>           <Text>
>             Association Types:{" "}
>             {association.associationTypes.map((type) => type.label).join(", ")}
>           </Text>
>           {Object.entries(association.properties).map(([key, value]) => (
>             <Text key={key}>
>               {key}: {value || "N/A"}
>             </Text>
>           ))}
>         </Flex>
>       ))}
>
>       <Flex direction="row" gap="sm">
>         <Button
>           onClick={pagination.previousPage}
>           disabled={!pagination.hasPreviousPage}
>           variant="secondary"
>         >
>           Previous Page
>         </Button>
>         <Button
>           onClick={pagination.nextPage}
>           disabled={!pagination.hasNextPage}
>           variant="primary"
>         >
>           Next Page
>         </Button>
>         <Button onClick={pagination.reset} variant="secondary">
>           Reset to First Page
>         </Button>
>         <Button onClick={refetch} variant="primary">
>           Fetch Latest Data
>         </Button>
>       </Flex>
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
> ```

### useAssociations

> [!WARNING]
>
> **Please note:** this hook is no longer available in the [latest version](https://developers.hubspot.com/docs/apps/developer-platform/add-features/ui-extensions/ui-extensions-sdk/versioning.md) (`v1`) of the UI extensions SDK. Instead, use the newer [`useRecordAssociationsCurrent`](#userecordassociationscurrent) hook instead.

The `useAssociations` hook fetches CRM records of a specific object type associated with the currently displaying record. It accepts an object containing configuration details for the association fetch request, and an optional object that formats returned property data.

> [tab] Call
>
> ```jsx theme={null}
> useAssociations(
>   {
>     // Object type ID to fetch associations for
>     toObjectType: "0-1",
>     // Optional properties to fetch from associated records
>     properties: ["firstname", "lastname", "email", "phone"],
>     // Optional pagination settings
>     pageLength: 25,
>   },
>   // Optional formatting configuration (same as useCrmProperties)
>   {
>     propertiesToFormat: "all",
>     formattingOptions: {
>       date: {
>         format: "MM-DD-YYYY",
>         relative: false,
>       },
>       dateTime: {
>         format: "MM-DD-YYYY hh:mm",
>         relative: false,
>       },
>       currency: {
>         addSymbol: true,
>       },
>     },
>   }
> );
> ```
>
> **config** `object` *required*
>
> Configures the association data fetch request with:
>
> * `toObjectType`: the object type ID to fetch associations from (e.g., '0-1' for contacts).
> * `properties`: an optional array of properties to fetch from associated records.
> * `pageLength`: an optional number of items per page (defaults to 10).
>
> **propertiesToFormat** `'all' | array` *required*
>
> Either `'all'` or an array of property names to format.
>
> **formattingOptions** `object`
>
> Contains formatting options for the values returned from date, datetime, and currency properties.
>
> * The `date` and `dateTime` objects can include `format` and `relative` subfields:
>   * `format` (string): a date or datetime string like `MM-DD-YYYY` or `MM-DD-YYYY:mm:ss`. Supports [standard date time string formats](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format).
>   * `relative` (boolean): set to `true` to display the amount of time passed since the returned value (e.g., `(1 day ago)` or `(1 hour ago)`).
> * The `currency` object can include `addSymbol` (boolean), which sets whether the currency symbol should display with the number. Set to `true` to display the currency symbol.

> [tab] Response
>
> ```jsx theme={null}
> {
>   isLoading: false,
>   error: null,
>   results: [
>     {
>       "toObjectId": 70284463640,
>       "associationTypes": [
>           {
>               "category": "HUBSPOT_DEFINED",
>               "typeId": 449,
>               "label": ""
>           }
>       ],
>       "properties": {
>           "email": "emailmaria@hubspot.com",
>           "firstname": "Maria",
>           "lastname": "Johnson (Sample Contact)"
>       }
>     }
>   ],
>   pagination: {
>     "hasNextPage": true,
>     "hasPreviousPage": false,
>     "currentPage": 1,
>     "pageSize": 1,
>     "nextPage": () => {}, // function to fetch results for next page
>     "previousPage": () => {}, // function to fetch results for previous page
>     "reset": () => {} // function to reset to page one of results
>   },
>   isRefetching: false,
>   refetch: () => {} // function to refetch the latest associations data
> }
> ```
>
> **isLoading** `boolean`
>
> Indicates whether the data is being fetched.
>
> **error** `object`
>
> For failed fetch requests, an object with error details. Will be `null` for successful requests.
>
> **results** `array`
>
> Association details of the returned CRM records. Includes the following fields:
>
> * `toObjectId`: the ID of the CRM record.
> * `associationTypes`: an array of [association type](https://developers.hubspot.com/docs/api-reference/latest/crm/associations/associate-records/guide.md) information.
> * `properties`: an object containing the requested property data, listed in alphabetical order. Values are returned unformatted unless `propertiesToFormat` is set. Datetime and date properties (e.g. `hs_timestamp`, `createdate`) are returned as millisecond-epoch strings.
>
> **pagination** `object`
>
> An object with pagination utilities, including:
>
> * `hasNextPage`: a boolean indicating if more pages are available.
> * `hasPreviousPage`: a boolean indicating if previous pages exist.
> * `currentPage`: the current page number.
> * `pageSize`: the number of items per page.
> * `nextPage()`: the function to go to next page.
> * `previousPage()`: the function to go to previous page.
> * `reset()`: the function to reset to first page.
>
> **isRefetching** `boolean`
>
> Indicates whether a refetch request is in progress.
>
> **refetch** `function`
>
> A function to refetch the latest associations data, with formatting applied as specified in the original hook call. The current page will be preserved.

> [tab] Example usage
>
> ```jsx wrap highlight={10-37} theme={null}
> import {
>   Text,
>   Button,
>   Flex,
>   hubspot
> } from "@hubspot/ui-extensions";
> import { useAssociations } from "@hubspot/ui-extensions/crm";
>
> const Extension = () => {
>   const { results, error, isLoading, pagination, isRefetching, refetch } = useAssociations(
>     {
>       // Object type ID to fetch associations for
>       toObjectType: '0-1',
>       // Optional properties to fetch from associated objects
>       properties: ['firstname', 'lastname', 'email', 'phone'],
>       // Optional pagination settings
>       pageLength: 25,
>     },
>     // Optional formatting configuration (same as useCrmProperties)
>     {
>       propertiesToFormat: 'all',
>       formattingOptions: {
>         date: {
>           format: 'MM-DD-YYYY',
>           relative: false
>         },
>         dateTime: {
>           format: 'MM-DD-YYYY hh:mm',
>           relative: false
>         },
>         currency: {
>           addSymbol: true
>         }
>       }
>     }
>   );
>
>   if (isLoading) {
>     return <Text>Loading associations...</Text>;
>   }
>
>   if (isRefetching) {
>     return <Text>Refetching associations...</Text>;
>   }
>
>   if (error) {
>     return <Text>Error loading associations: {error.message}</Text>;
>   }
>
>   return (
>     <Flex direction="column" gap="medium">
>       <Text>Associations (Page {pagination.currentPage})</Text>
>
>       {results.map((association, index) => (
>         <Flex direction="column" key={association.toObjectId}>
>           <Text>Association {index + 1}: Object ID {association.toObjectId}</Text>
>           <Text>
>             Association Types: {association.associationTypes.map(type => type.label).join(', ')}
>           </Text>
>           {Object.entries(association.properties).map(([key, value]) => (
>             <Text key={key}>{key}: {value || 'N/A'}</Text>
>           ))}
>         </Flex>
>       ))}
>
>       <Flex direction="row" gap="sm">
>         <Button
>           onClick={pagination.previousPage}
>           disabled={!pagination.hasPreviousPage}
>           variant="secondary"
>         >
>           Previous Page
>         </Button>
>         <Button
>           onClick={pagination.nextPage}
>           disabled={!pagination.hasNextPage}
>           variant="primary"
>         >
>           Next Page
>         </Button>
>         <Button
>           onClick={pagination.reset}
>           variant="secondary"
>         >
>           Reset to First Page
>         </Button>
>         <Button
>           onClick={refetch}
>           variant="primary"
>         >
>           Fetch Latest Data
>         </Button>
>       </Flex>
>     </Flex>
>   );
> };
>
> hubspot.extend(() => <Extension />);
>
> ```

## Best practices

### Always use TypeScript generics

```tsx theme={null}
// ✅ Good - Typed for better IntelliSense and type safety
const actions = useExtensionActions<'crm.record.tab'>();
const context = useExtensionContext<'crm.record.tab'>();

// ❌ Avoid - Less type safety and IntelliSense
const actions = useExtensionActions();
const context = useExtensionContext();
```

### Extract hook calls to component level

```tsx theme={null}
// ✅ Good - Hooks at component level
function MyExtension() {
  const { addAlert } = useExtensionActions<'crm.record.tab'>();
  const context = useExtensionContext<'crm.record.tab'>();

  const handleClick = () => {
    addAlert({ message: `Action from ${context.location}` });
  };

  return <Button onClick={handleClick}>Click me</Button>;
}

// ❌ Avoid - Don't call hooks in event handlers
function MyExtension() {
  const handleClick = () => {
    const { addAlert } = useExtensionActions(); // Wrong!
    addAlert({ message: "Hello" });
  };

  return <Button onClick={handleClick}>Click me</Button>;
}
```
