--- title: React Hooks label: React Hooks order: 30 desc: Make use of all of the powerful React hooks that Payload provides. keywords: admin, components, custom, documentation, Content Management System, cms, headless, javascript, node, react, express --- Payload provides a variety of powerful hooks that can be used within your own React components. With them, you can interface with Payload itself and build just about any type of complex customization you can think of—directly in familiar React code. ## useField The `useField` hook is used internally within every applicable Payload field component, and it manages sending and receiving a field's state from its parent form. Outside of internal use, its most common use-case is in custom `Field` components. When you build a custom React `Field` component, you'll be responsible for sending and receiving the field's `value` from the form itself. To do so, import the `useField` hook as follows: ```tsx import { useField } from 'payload/components/forms' type Props = { path: string } const CustomTextField: React.FC = ({ path }) => { // highlight-start const { value, setValue } = useField({ path }) // highlight-end return setValue(e.target.value)} value={value.path} /> } ``` The `useField` hook accepts an `args` object and sends back information and helpers for you to make use of: ```ts const field = useField({ path: 'fieldPathHere', // required validate: myValidateFunc, // optional disableFormData?: false, // if true, the field's data will be ignored condition?: myConditionHere, // optional, used to skip validation if condition fails }) // Here is what `useField` sends back const { showError, // whether or not the field should show as errored errorMessage, // the error message to show, if showError value, // the current value of the field from the form formSubmitted, // if the form has been submitted formProcessing, // if the form is currently processing setValue, // method to set the field's value in form state initialValue, // the initial value that the field mounted with } = field; // The rest of your component goes here ``` ## useFormFields There are times when a custom field component needs to have access to data from other fields, and you have a few options to do so. The `useFormFields` hook is a powerful and highly performant way to retrieve a form's field state, as well as to retrieve the `dispatchFields` method, which can be helpful for setting other fields' form states from anywhere within a form. This hook is great for retrieving only certain fields from form state because it ensures that it will only cause a rerender when the items that you ask for change. Thanks to the awesome package [`use-context-selector`](https://github.com/dai-shi/use-context-selector), you can retrieve a specific field's state easily. This is ideal because you can ensure you have an up-to-date field state, and your component will only re-render when _that field's state_ changes. You can pass a Redux-like selector into the hook, which will ensure that you retrieve only the field that you want. The selector takes an argument with type of `[fields: Fields, dispatch: React.Dispatch]]`. ```tsx import { useFormFields } from 'payload/components/forms' const MyComponent: React.FC = () => { // Get only the `amount` field state, and only cause a rerender when that field changes const amount = useFormFields(([fields, dispatch]) => fields.amount) // Do the same thing as above, but to the `feePercentage` field const feePercentage = useFormFields(([fields, dispatch]) => fields.feePercentage) if (typeof amount?.value !== 'undefined' && typeof feePercentage?.value !== 'undefined') { return The fee is ${(amount.value * feePercentage.value) / 100} } } ``` ## useAllFormFields **To retrieve more than one field**, you can use the `useAllFormFields` hook. Your component will re-render when _any_ field changes, so use this hook only if you absolutely need to. Unlike the `useFormFields` hook, this hook does not accept a "selector", and it always returns an array with type of `[fields: Fields, dispatch: React.Dispatch]]`. You can do lots of powerful stuff by retrieving the full form state, like using built-in helper functions to reduce field state to values only, or to retrieve sibling data by path. ```tsx import { useAllFormFields, reduceFieldsToValues, getSiblingData } from 'payload/components/forms'; const ExampleComponent: React.FC = () => { // the `fields` const will be equal to all fields' state, // and the `dispatchFields` method is usable to send field state up to the form const [fields, dispatchFields] = useAllFormFields(); // Pass in fields, and indicate if you'd like to "unflatten" field data. // The result below will reflect the data stored in the form at the given time const formData = reduceFieldsToValues(fields, true); // Pass in field state and a path, // and you will be sent all sibling data of the path that you've specified const siblingData = getSiblingData(fields, 'someFieldName'); return ( // return some JSX here if necessary ) }; ``` #### Updating other fields' values If you are building a custom component, then you should use `setValue` which is returned from the `useField` hook to programmatically set your field's value. But if you're looking to update _another_ field's value, you can use `dispatchFields` returned from `useFormFields`. You can send the following actions to the `dispatchFields` function. | Action | Description | | ---------------------- | -------------------------------------------------------------------------- | | **`ADD_ROW`** | Adds a row of data (useful in array / block field data) | | **`DUPLICATE_ROW`** | Duplicates a row of data (useful in array / block field data) | | **`MODIFY_CONDITION`** | Updates a field's conditional logic result (true / false) | | **`MOVE_ROW`** | Moves a row of data (useful in array / block field data) | | **`REMOVE`** | Removes a field from form state | | **`REMOVE_ROW`** | Removes a row of data from form state (useful in array / block field data) | | **`REPLACE_STATE`** | Completely replaces form state | | **`UPDATE`** | Update any property of a specific field's state | To see types for each action supported within the `dispatchFields` hook, check out the Form types [here](https://github.com/payloadcms/payload/blob/main/packages/payload/src/admin/components/forms/Form/types.ts). ## useForm The `useForm` hook can be used to interact with the form itself, and sends back many methods that can be used to reactively fetch form state without causing rerenders within your components each time a field is changed. This is useful if you have action-based callbacks that your components fire, and need to interact with form state _based on a user action_. Warning:
This hook is optimized to avoid causing rerenders when fields change, and as such, its `fields` property will be out of date. You should only leverage this hook if you need to perform actions against the form in response to your users' actions. Do not rely on its returned "fields" as being up-to-date. They will be removed from this hook's response in an upcoming version.
The `useForm` hook returns an object with the following properties: | fields, }, { value: "Deprecated. This property cannot be relied on as up-to-date.", }, { value: '' } ], [ { value: submit, }, { value: "Method to trigger the form to submit", }, { value: '' } ], [ { value: dispatchFields, }, { value: "Dispatch actions to the form field state", }, { value: '' } ], [ { value: validateForm, }, { value: "Trigger a validation of the form state", }, { value: '' } ], [ { value: createFormData, }, { value: <>Create a multipart/form-data object from the current form's state, }, { value: '' } ], [ { value: disabled, }, { value: "Boolean denoting whether or not the form is disabled", }, { value: '' } ], [ { value: getFields, }, { value: 'Gets all fields from state', }, { value: '', } ], [ { value: getField, }, { value: 'Gets a single field from state by path', }, { value: '', }, ], [ { value: getData, }, { value: 'Returns the data stored in the form', }, { value: '', }, ], [ { value: getSiblingData, }, { value: 'Returns form sibling data for the given field path', }, { value: '', }, ], [ { value: setModified, }, { value: <>Set the form\'s modified state, }, { value: '', }, ], [ { value: setProcessing, }, { value: <>Set the form\'s processing state, }, { value: '', }, ], [ { value: setSubmitted, }, { value: <>Set the form\'s submitted state, }, { value: '', }, ], [ { value: formRef, }, { value: 'The ref from the form HTML element', }, { value: '', }, ], [ { value: reset, }, { value: 'Method to reset the form to its initial state', }, { value: '', }, ], [ { value: addFieldRow, }, { value: "Method to add a row on an array or block field", }, { drawerTitle: 'addFieldRow', drawerDescription: 'A useful method to programmatically add a row to an array or block field.', drawerSlug: 'addFieldRow', drawerContent: ( <> path, }, { value: "The path to the array or block field", }, ], [ { value: rowIndex, }, { value: "The index of the row to add. If omitted, the row will be added to the end of the array.", }, ], [ { value: data, }, { value: "The data to add to the row", }, ], ]} /> {' '}
{' '}
  {`import { useForm } from "payload/components/forms";

export const CustomArrayManager = () => {
  const { addFieldRow } = useForm()

  return (
    
  )
}`}

An example config to go along with the custom component

{`const ExampleCollection = {
  slug: "example-collection",
  fields: [
    {
      name: "arrayField",
      type: "array",
      fields: [
        {
          name: "textField",
          type: "text",
        },
      ],
    },
    {
      type: "ui",
      name: "customArrayManager",
      admin: {
        components: {
          Field: CustomArrayManager,
        },
      },
    },
  ],
}`}
  
) } ], [ { value: removeFieldRow, }, { value: "Method to remove a row from an array or block field", }, { drawerTitle: 'removeFieldRow', drawerDescription: 'A useful method to programmatically remove a row from an array or block field.', drawerSlug: 'removeFieldRow', drawerContent: ( <> path, }, { value: "The path to the array or block field", }, ], [ { value: rowIndex, }, { value: "The index of the row to remove", }, ], ]} /> {' '}
{' '}
  {`import { useForm } from "payload/components/forms";

export const CustomArrayManager = () => {
  const { removeFieldRow } = useForm()

  return (
    
  )
}`}

An example config to go along with the custom component

{`const ExampleCollection = {
  slug: "example-collection",
  fields: [
    {
      name: "arrayField",
      type: "array",
      fields: [
        {
          name: "textField",
          type: "text",
        },
      ],
    },
    {
      type: "ui",
      name: "customArrayManager",
      admin: {
        components: {
          Field: CustomArrayManager,
        },
      },
    },
  ],
}`}
  
) } ], [ { value: replaceFieldRow, }, { value: "Method to replace a row from an array or block field", }, { drawerTitle: 'replaceFieldRow', drawerDescription: 'A useful method to programmatically replace a row from an array or block field.', drawerSlug: 'replaceFieldRow', drawerContent: ( <> path, }, { value: "The path to the array or block field", }, ], [ { value: rowIndex, }, { value: "The index of the row to replace", }, ], [ { value: data, }, { value: "The data to replace within the row", }, ], ]} /> {' '}
{' '}
  {`import { useForm } from "payload/components/forms";

export const CustomArrayManager = () => {
  const { replaceFieldRow } = useForm()

  return (
    
  )
}`}

An example config to go along with the custom component

{`const ExampleCollection = {
  slug: "example-collection",
  fields: [
    {
      name: "arrayField",
      type: "array",
      fields: [
        {
          name: "textField",
          type: "text",
        },
      ],
    },
    {
      type: "ui",
      name: "customArrayManager",
      admin: {
        components: {
          Field: CustomArrayManager,
        },
      },
    },
  ],
}`}
  
) } ], ]} /> ## useCollapsible The `useCollapsible` hook allows you to control parent collapsibles: | Property | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------ | --- | | **`isCollapsed`** | State of the collapsible. `true` if open, `false` if collapsed | | **`isVisible`** | If nested, determine if the nearest collapsible is visible. `true` if no parent is closed, `false` otherwise | | **`toggle`** | Toggles the state of the nearest collapsible | | **`isWithinCollapsible`** | Determine when you are within another collaspible | | **Example:** ```tsx import React from 'react' import { useCollapsible } from 'payload/components/utilities' const CustomComponent: React.FC = () => { const { isCollapsed, toggle } = useCollapsible() return (

I am {isCollapsed ? 'closed' : 'open'}

) } ``` ## useDocumentInfo The `useDocumentInfo` hook provides lots of information about the document currently being edited, including the following: | Property | Description | | ------------------------- | ------------------------------------------------------------------------------------------------------------------ | | **`collection`** | If the doc is a collection, its collection config will be returned | | **`global`** | If the doc is a global, its global config will be returned | | **`id`** | If the doc is a collection, its ID will be returned | | **`preferencesKey`** | The `preferences` key to use when interacting with document-level user preferences | | **`versions`** | Versions of the current doc | | **`unpublishedVersions`** | Unpublished versions of the current doc | | **`publishedDoc`** | The currently published version of the doc being edited | | **`getVersions`** | Method to trigger the retrieval of document versions | | **`docPermissions`** | The current documents permissions. Collection document permissions fallback when no id is present (i.e. on create) | | **`getDocPermissions`** | Method to trigger the retrieval of document level permissions | **Example:** ```tsx import { useDocumentInfo } from 'payload/components/utilities' const LinkFromCategoryToPosts: React.FC = () => { // highlight-start const { id } = useDocumentInfo() // highlight-end // id will be undefined on the create form if (!id) { return null } return ( View posts ) } ``` ## useLocale In any custom component you can get the selected locale object with the `useLocale` hook. `useLocale`gives you the full locale object, consisting of a `label`, `rtl`(right-to-left) property, and then `code`. Here is a simple example: ```tsx import { useLocale } from 'payload/components/utilities' const Greeting: React.FC = () => { // highlight-start const locale = useLocale() // highlight-end const trans = { en: 'Hello', es: 'Hola', } return {trans[locale.code]} } ``` ## useAuth Useful to retrieve info about the currently logged in user as well as methods for interacting with it. It sends back an object with the following properties: | Property | Description | | ------------------------ | --------------------------------------------------------------------------------------- | | **`user`** | The currently logged in user | | **`logOut`** | A method to log out the currently logged in user | | **`refreshCookie`** | A method to trigger the silent refreshing of a user's auth token | | **`setToken`** | Set the token of the user, to be decoded and used to reset the user and token in memory | | **`token`** | The logged in user's token (useful for creating preview links, etc.) | | **`refreshPermissions`** | Load new permissions (useful when content that effects permissions has been changed) | | **`permissions`** | The permissions of the current user | ```tsx import { useAuth } from 'payload/components/utilities' import { User } from '../payload-types.ts' const Greeting: React.FC = () => { // highlight-start const { user } = useAuth() // highlight-end return Hi, {user.email}! } ``` ## useConfig Used to easily fetch the full Payload config. ```tsx import { useConfig } from 'payload/components/utilities' const MyComponent: React.FC = () => { // highlight-start const config = useConfig() // highlight-end return {config.serverURL} } ``` ## useEditDepth Sends back how many editing levels "deep" the current component is. Edit depth is relevant while adding new documents / editing documents in modal windows and other cases. ```tsx import { useEditDepth } from 'payload/components/utilities' const MyComponent: React.FC = () => { // highlight-start const editDepth = useEditDepth() // highlight-end return My component is {editDepth} levels deep } ``` ## usePreferences Returns methods to set and get user preferences. More info can be found [here](https://payloadcms.com/docs/admin/preferences). ## useTheme Returns the currently selected theme (`light`, `dark` or `auto`), a set function to update it and a boolean `autoMode`, used to determine if the theme value should be set automatically based on the user's device preferences. ```tsx import { useTheme } from 'payload/components/utilities' const MyComponent: React.FC = () => { // highlight-start const { autoMode, setTheme, theme } = useTheme() // highlight-end return ( <> The current theme is {theme} and autoMode is {autoMode} ) } ``` ## useTableColumns Returns methods to manipulate table columns ```tsx import { useTableColumns } from 'payload/components/hooks' const MyComponent: React.FC = () => { // highlight-start const { setActiveColumns } = useTableColumns() const resetColumns = () => { setActiveColumns(['id', 'createdAt', 'updatedAt']) } // highlight-end return ( ) } ``` ## useDocumentEvents The `useDocumentEvents` hook provides a way of subscribing to cross-document events, such as updates made to nested documents within a drawer. This hook will report document events that are outside the scope of the document currently being edited. This hook provides the following: | Property | Description | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | **`mostRecentUpdate`** | An object containing the most recently updated document. It contains the `entitySlug`, `id` (if collection), and `updatedAt` properties | | **`reportUpdate`** | A method used to report updates to documents. It accepts the same arguments as the `mostRecentUpdate` property. | **Example:** ```tsx import { useDocumentEvents } from 'payload/components/hooks' const ListenForUpdates: React.FC = () => { const { mostRecentUpdate } = useDocumentEvents() return {JSON.stringify(mostRecentUpdate)} } ``` Right now the `useDocumentEvents` hook only tracks recently updated documents, but in the future it will track more document-related events as needed, such as document creation, deletion, etc.