# Controllers and stores

# Controllers and stores

Some Mantine components can be driven with a hook. Call `use<Component>` in your component,
get back an object with actions and queries, and pass it to the component with a prop. There are
two kinds of these objects:

* A controller is passed with the `controller` prop. It adds actions and queries to a component
  that you use as is, for example `expandAll()` on `Accordion` or `next()` on `Stepper`.
* A store is passed with the `store` prop. It is a building block for your own component,
  for example `useSelect` lets you build a custom select on top of `Select`.

Both are optional. Every component works without them with `value`, `defaultValue` and `onChange`
props, see [Controlled vs Uncontrolled](https://alpha.mantine.dev/llms/guides-controlled-vs-uncontrolled.md).

## Controllers

A controller owns the component state. Create it with the hook, pass the same state options
that the component accepts as props, and pass the result to the `controller` prop:

```tsx
import { Accordion, Button, useAccordion } from '@mantine/core';

function Demo() {
  const controller = useAccordion({ multiple: true, defaultValue: ['first'] });

  return (
    <>
      <Button onClick={controller.expandAll}>Expand all</Button>
      <Button onClick={controller.collapseAll}>Collapse all</Button>

      <Accordion controller={controller}>
        <Accordion.Item value="first">{/* ... */}</Accordion.Item>
        <Accordion.Item value="second">{/* ... */}</Accordion.Item>
      </Accordion>
    </>
  );
}
```

Use a controller when props are not enough:

* To call an action that depends on state the component owns internally, for example `expandAll()`
  needs the list of mounted items.
* To drive the component from outside its subtree, for example from a toolbar or a keyboard
  shortcut handler.
* To read state that `onChange` does not report, for example `isExpanded(item)` or `getItems()`.

Each component documents the actions and queries of its controller on its own page, see the
[list of components](#components-with-controllers) below.

## Stores

A store is created with a `use<Component>` hook and passed to the `store` prop. Use it as a base
for your own component with its own props and behavior. For example, `useSelect` reuses the value,
search and dropdown handling of `Select` to build a select that offers to create an option from the
search text:

```tsx
import { Select, useSelect } from '@mantine/core';

interface CreatableSelectProps {
  data: string[];
  onCreate: (item: string) => void;
}

function CreatableSelect({ data, onCreate }: CreatableSelectProps) {
  const store = useSelect({
    onChange: (item) => {
      if (item !== null && !data.includes(item)) {
        onCreate(item);
      }
    },
  });

  const search = store.getSearch().trim();
  const canCreate = search !== '' && !data.includes(search);

  return <Select store={store} searchable data={canCreate ? [...data, search] : data} />;
}
```

`Combobox`, `Tree` and `DataGrid` are building blocks by design, so they work with a store as
well, see the [list of components](#components-with-stores) below.

## Controller and props

When the `controller` prop is set, the controller owns the state and the state props of the
component are ignored. Pass them to the hook instead:

```tsx
import { Accordion, useAccordion } from '@mantine/core';

// ✅ State options go to the hook
const controller = useAccordion({ multiple: true, defaultValue: ['first'] });
<Accordion controller={controller} />;

// ❌ multiple and defaultValue are ignored, the controller already owns them
const controller = useAccordion();
<Accordion controller={controller} multiple defaultValue={['first']} />;
```

The `controller` prop description in the props table of each component lists the props it
replaces. Other props, for example `size`, `variant` and `classNames`, work the same way
with and without a controller. The same rules apply to the `store` prop.

## Usage with forms

`form.getInputProps('field')` from [@mantine/form](https://alpha.mantine.dev/llms/form-use-form.md) returns value, change handler
and other props for the component. How they combine with a controller depends on whether
the controller owns the value.

Most controllers do not own the value. For example, `@mantine/dates` controllers own the displayed
date, level and dropdown state, while the selected value stays on the component. For these
components, spread `form.getInputProps()` on the component and pass the controller next to it:

```tsx
import { DateInput, useDateInput } from '@mantine/dates';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({ initialValues: { date: null } });
  const controller = useDateInput();

  return (
    <DateInput controller={controller} {...form.getInputProps('date')} />
  );
}
```

`usePinInput`, `useTimePicker` and `useMaskedDateInput` own the value, so `form.getInputProps()`
cannot be spread on the component. Instead, create a wrapper component: it passes the props
that the controller replaces to the hook and forwards the rest to the component:

```tsx
import { useState } from 'react';
import {
  Button,
  Code,
  Group,
  Input,
  PinInput,
  PinInputProps,
  Stack,
  Text,
  usePinInput,
} from '@mantine/core';
import { useForm } from '@mantine/form';

function PinField({
  value,
  defaultValue,
  onChange,
  onComplete,
  length,
  error,
  ...others
}: Omit<PinInputProps, 'controller' | 'error'> & { error?: React.ReactNode }) {
  const controller = usePinInput({ value, defaultValue, onChange, onComplete, length });

  const handleClear = () => {
    controller.clear();
    controller.focus(0);
  };

  return (
    <Stack gap="xs">
      <Group>
        <PinInput controller={controller} error={!!error} {...others} />
        <Button variant="default" onClick={handleClear} disabled={!controller.getValue()}>
          Clear
        </Button>
      </Group>
      {error && <Input.Error>{error}</Input.Error>}
    </Stack>
  );
}

function Demo() {
  const [submitted, setSubmitted] = useState<string | null>(null);
  const form = useForm({
    initialValues: { code: '' },
    validate: { code: (value) => (/^\\d{6}$/.test(value) ? null : 'Enter all 6 digits') },
  });

  return (
    <form onSubmit={form.onSubmit((values) => setSubmitted(values.code))}>
      <Stack>
        <PinField length={6} type="number" {...form.getInputProps('code')} />

        <Text size="sm">
          Submitted code: <Code>{submitted ?? 'none'}</Code>
        </Text>

        <Group>
          <Button type="submit">Submit</Button>
          <Button variant="default" onClick={() => form.setFieldValue('code', '123456')}>
            Set 123456
          </Button>
          <Button variant="default" onClick={form.reset}>
            Reset
          </Button>
        </Group>
      </Stack>
    </form>
  );
}
```


The pattern has three rules:

* Pass every prop that the `controller` prop replaces to the hook, not only `value`,
  `defaultValue` and `onChange`. For example, `length` of `PinInput` and `format` of `TimePicker`
  are ignored on the component once a controller is set.
* Keep `error`, `onFocus` and `onBlur` on the component.
* Pass `onChange` to the hook as is, so that `form.reset()` clears a partially entered value.

Controller actions, for example `clear()` or `setValue()`, call `onChange` the same way as typing,
so the form stays in sync.

Inside the wrapper you can use controller queries that the form cannot see.
For example, the form treats an incomplete time as empty, while `controller.hasValue()` knows that
the user has started typing:

```tsx
import { useState } from 'react';
import { Button, Code, Group, Stack, Text } from '@mantine/core';
import { TimePicker, TimePickerProps, useTimePicker } from '@mantine/dates';
import { useForm } from '@mantine/form';

function TimeField({
  value,
  defaultValue,
  onChange,
  type,
  format,
  amPmLabels,
  withSeconds,
  min,
  max,
  pasteSplit,
  error,
  ...others
}: Omit<TimePickerProps, 'controller'>) {
  const controller = useTimePicker({
    value,
    defaultValue,
    onChange,
    type,
    format,
    amPmLabels,
    withSeconds,
    min,
    max,
    pasteSplit,
  });

  return (
    <TimePicker
      controller={controller}
      error={error && controller.hasValue() ? 'Finish entering the time' : error}
      {...others}
    />
  );
}

function Demo() {
  const [submitted, setSubmitted] = useState<string | null>(null);
  const form = useForm({
    initialValues: { time: '' },
    validate: { time: (value) => (value ? null : 'Time is required') },
  });

  return (
    <form onSubmit={form.onSubmit((values) => setSubmitted(values.time))}>
      <Stack>
        <TimeField label="Start time" {...form.getInputProps('time')} />

        <Text size="sm">
          Submitted value: <Code>{submitted || 'none'}</Code>
        </Text>

        <Group>
          <Button type="submit">Submit</Button>
          <Button variant="default" onClick={() => form.setFieldValue('time', '09:30')}>
            Set 09:30
          </Button>
          <Button variant="default" onClick={form.reset}>
            Reset
          </Button>
        </Group>
      </Stack>
    </form>
  );
}
```


The same component works with other form libraries. With
[react-hook-form](https://react-hook-form.com/), pass the `field` props of `Controller`:

```tsx
import { Controller, useForm } from 'react-hook-form';

function Demo() {
  const { control, handleSubmit } = useForm({ defaultValues: { code: '' } });

  return (
    <form onSubmit={handleSubmit((values) => console.log(values))}>
      <Controller
        name="code"
        control={control}
        rules={{ minLength: 6 }}
        render={({ field, fieldState }) => (
          <PinField
            length={6}
            value={field.value}
            onChange={field.onChange}
            onBlur={field.onBlur}
            error={fieldState.error ? 'Enter all 6 digits' : null}
          />
        )}
      />
    </form>
  );
}
```

## Reading state

The component that called the hook rerenders when the state changes, so queries can be used during render:

```tsx
import { Accordion, Button, Text, useAccordion } from '@mantine/core';

function Demo() {
  const controller = useAccordion({ multiple: true });
  const expanded = controller.getExpandedItems();

  return (
    <>
      <Text>{expanded.length} items expanded</Text>
      <Button disabled={expanded.length === 0} onClick={controller.collapseAll}>
        Collapse all
      </Button>
      <Accordion controller={controller}>{/* items */}</Accordion>
    </>
  );
}
```

Actions and queries keep the same reference for the lifetime of the controller.
They are safe as effect dependencies and as props of memoized components, and queries always return the latest value:

```tsx
import { useEffect } from 'react';
import { useStepper } from '@mantine/core';

function Demo() {
  const controller = useStepper();

  useEffect(() => {
    const handler = (event: KeyboardEvent) => {
      if (event.key === 'ArrowRight') {
        controller.next();
      }
    };

    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [controller.next]);

  return null;
}
```

Queries that depend on rendered children, for example `getItems()` on `Accordion` or
`getStepCount()` on `Stepper`, return an empty result before the component is rendered.
Stores work the same way, except `useDataGrid`, which returns a new object on every render.

## TypeScript

Controller and store types are named after the component and exported from the same package as
the hook. Use them to type a controller that is created in one component and passed to another:

```tsx
import { Accordion, useAccordion } from '@mantine/core';
import type { AccordionController, AccordionControllerOptions } from '@mantine/core';

interface SettingsAccordionProps {
  controller: AccordionController<true>;
}

function SettingsAccordion({ controller }: SettingsAccordionProps) {
  return <Accordion controller={controller}>{/* items */}</Accordion>;
}

function useSettingsAccordion(options: AccordionControllerOptions<true>) {
  return useAccordion({ ...options, multiple: true });
}

function Demo() {
  const controller = useSettingsAccordion({ defaultValue: ['profile'] });
  return <SettingsAccordion controller={controller} />;
}
```

When the state type depends on an option, the type is inferred from the options
passed to the hook:

```tsx
import { useAccordion } from '@mantine/core';

const single = useAccordion();
single.getValue(); // -> string | null

const multiple = useAccordion({ multiple: true });
multiple.getValue(); // -> string[]
```

## Components with controllers

`@mantine/core`:

* [Accordion](https://alpha.mantine.dev/llms/core-accordion.md#controlling-with-useaccordion), `useAccordion`
* [Editable](https://alpha.mantine.dev/llms/core-editable.md#useeditable-hook), `useEditable`
* [ImageCropper](https://alpha.mantine.dev/llms/core-image-cropper.md#useimagecropper-hook), `useImageCropper`
* [Menubar](https://alpha.mantine.dev/llms/core-menubar.md#controlling-with-usemenubar), `useMenubar`
* [Pagination](https://alpha.mantine.dev/llms/core-pagination.md#controlling-with-usepagination), `usePagination`, also exported
  from `@mantine/hooks`
* [PinInput](https://alpha.mantine.dev/llms/core-pin-input.md#controlling-with-usepininput), `usePinInput`
* [Stepper](https://alpha.mantine.dev/llms/core-stepper.md#controlling-with-usestepper), `useStepper`
* [Timer](https://alpha.mantine.dev/llms/core-timer.md#usetimer-hook), `useTimer`

`@mantine/dates`:

* [Calendar](https://alpha.mantine.dev/llms/dates-calendar.md#controlling-with-usecalendar),
  [DatePicker](https://alpha.mantine.dev/llms/dates-date-picker.md#controlling-with-usecalendar),
  [MonthPicker](https://alpha.mantine.dev/llms/dates-month-picker.md#controlling-with-usecalendar),
  [YearPicker](https://alpha.mantine.dev/llms/dates-year-picker.md#controlling-with-usecalendar),
  [WeekPicker](https://alpha.mantine.dev/llms/dates-week-picker.md#controlling-with-usecalendar) and
  [QuarterPicker](https://alpha.mantine.dev/llms/dates-quarter-picker.md#controlling-with-usecalendar), `useCalendar`
* [DatePickerInput](https://alpha.mantine.dev/llms/dates-date-picker-input.md#controlling-with-usedatepickerinput),
  `useDatePickerInput`
* [MonthPickerInput](https://alpha.mantine.dev/llms/dates-month-picker-input.md#controlling-with-usemonthpickerinput),
  `useMonthPickerInput`
* [YearPickerInput](https://alpha.mantine.dev/llms/dates-year-picker-input.md#controlling-with-useyearpickerinput),
  `useYearPickerInput`
* [WeekPickerInput](https://alpha.mantine.dev/llms/dates-week-picker-input.md#controlling-with-useweekpickerinput),
  `useWeekPickerInput`
* [QuarterPickerInput](https://alpha.mantine.dev/llms/dates-quarter-picker-input.md#controlling-with-usequarterpickerinput),
  `useQuarterPickerInput`
* [DateInput](https://alpha.mantine.dev/llms/dates-date-input.md#controlling-with-usedateinput), `useDateInput`
* [MaskedDateInput](https://alpha.mantine.dev/llms/dates-masked-date-input.md#controlling-with-usemaskeddateinput),
  `useMaskedDateInput`
* [DateTimePicker](https://alpha.mantine.dev/llms/dates-date-time-picker.md#controlling-with-usedatetimepicker),
  `useDateTimePicker`
* [InlineDateTimePicker](https://alpha.mantine.dev/llms/dates-inline-date-time-picker.md#controlling-with-useinlinedatetimepicker),
  `useInlineDateTimePicker`
* [TimePicker](https://alpha.mantine.dev/llms/dates-time-picker.md#controlling-with-usetimepicker), `useTimePicker`

## Components with stores

* [Autocomplete](https://alpha.mantine.dev/llms/core-autocomplete.md#building-on-autocomplete-with-useautocomplete),
  `useAutocomplete`
* [Combobox](https://alpha.mantine.dev/llms/core-combobox.md#usecombobox-hook), `useCombobox`
* [MultiSelect](https://alpha.mantine.dev/llms/core-multi-select.md#building-on-multiselect-with-usemultiselect), `useMultiSelect`
* [Select](https://alpha.mantine.dev/llms/core-select.md#building-on-select-with-useselect), `useSelect`
* [TagsInput](https://alpha.mantine.dev/llms/core-tags-input.md#building-on-tagsinput-with-usetagsinput), `useTagsInput`
* [Tree](https://alpha.mantine.dev/llms/core-tree.md#usetree-hook), `useTree`
* [DataGrid](https://alpha.mantine.dev/llms/data-grid-getting-started.md#store-hook), `useDataGrid`, exported from
  `@mantine/data-grid`
