Watching values

Subscribe to form value changes with onValuesChange, watch and useWatchValue

Usage

useForm provides several ways to react to value changes. Pick the one that matches the task:

  • form.getValues() – read the current values in an event handler, see Form values
  • form.useWatchValue(path) – render a part of the form based on a field value
  • form.watch(path, callback) – run an effect when a field changes
  • onValuesChange option – react to any change in the form, for example to save values to local storage

form.useWatchValue

form.useWatchValue returns the current value of a field and rerenders the component only when that field changes. Use it to render a part of the form based on a value:

import { Checkbox, Collapse, Stack, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      email: '',
      shipsInternationally: false,
      country: '',
    },
  });

  const shipsInternationally = form.useWatchValue('shipsInternationally');

  return (
    <Stack>
      <TextInput
        label="Email"
        placeholder="Email"
        {...form.getInputProps('email')}
      />

      <Checkbox
        label="Ships internationally"
        {...form.getInputProps('shipsInternationally', { type: 'checkbox' })}
      />

      <Collapse expanded={shipsInternationally}>
        <TextInput
          label="Country"
          placeholder="Country"
          {...form.getInputProps('country')}
        />
      </Collapse>
    </Stack>
  );
}

Do not read values with form.getValues() during render, it does not rerender the component when the value changes:

import { Collapse } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: { shipsInternationally: false },
  });

  // ❌ Does not rerender the component when the value changes
  const staleValue = form.getValues().shipsInternationally;

  // ✅ Rerenders the component when the value changes
  const shipsInternationally = form.useWatchValue('shipsInternationally');

  return <Collapse expanded={shipsInternationally}>{/* ... */}</Collapse>;
}

form.useWatchValue is a hook, it cannot be called conditionally or inside loops:

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: { name: '' },
  });

  // ❌ This will not work
  if (Math.random() > 0.5) {
    const name = form.useWatchValue('name');
  }
}

form.watch

form.watch runs a callback when a field changes. The callback receives the new value, previous value, touched and dirty states:

import { TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
  });

  form.watch('name', ({ previousValue, value, touched, dirty }) => {
    console.log({ previousValue, value, touched, dirty });
  });

  return (
    <div>
      <TextInput label="Name" placeholder="Name" {...form.getInputProps('name')} />
      <TextInput mt="md" label="Email" placeholder="Email" {...form.getInputProps('email')} />
    </div>
  );
}

form.watch is a hook, it cannot be called conditionally or inside loops:

import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: { name: '' },
  });

  // ❌ This will not work
  if (Math.random() > 0.5) {
    form.watch('name', ({ previousValue, value, touched, dirty }) => {
      console.log({ previousValue, value, touched, dirty });
    });
  }
}

form.watch with arrays

With array fields, the callback is called when any nested field changes or when a list handler is called:

Total: $11

import { useState } from 'react';
import { Button, Group, NumberInput, Stack, Text, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';
import { randomId } from '@mantine/hooks';

interface Product {
  name: string;
  price: number;
  quantity: number;
  key: string;
}

const getTotal = (products: Product[]) =>
  products.reduce((acc, item) => acc + item.price * item.quantity, 0);

function Demo() {
  const form = useForm<{ products: Product[] }>({
    initialValues: {
      products: [
        { name: 'Apple', price: 2, quantity: 3, key: randomId() },
        { name: 'Orange', price: 1, quantity: 5, key: randomId() },
      ],
    },
  });

  const [total, setTotal] = useState(() => getTotal(form.getValues().products));

  form.watch('products', ({ value }) => setTotal(getTotal(value)));

  return (
    <Stack>
      <Text fw={700}>Total: ${total}</Text>
      {form.getValues().products.map((item, index) => (
        <Group key={item.key} align="flex-end">
          <TextInput
            label="Name"
            style={{ flex: 1 }}
            {...form.getInputProps(`products.${index}.name`)}
          />
          <NumberInput
            label="Price"
            style={{ width: 80 }}
            {...form.getInputProps(`products.${index}.price`)}
          />
          <NumberInput
            label="Qty"
            style={{ width: 80 }}
            {...form.getInputProps(`products.${index}.quantity`)}
          />
          <Button
            color="red"
            onClick={() => form.removeListItem('products', index)}
          >
            Remove
          </Button>
        </Group>
      ))}
      <Group>
        <Button
          onClick={() =>
            form.insertListItem('products', {
              name: '',
              price: 0,
              quantity: 1,
              key: randomId(),
            })
          }
        >
          Add product
        </Button>
      </Group>
    </Stack>
  );
}

form.watch cascade

A watcher of a parent path is called when a nested field changes. The reverse is not true: form.setFieldValue on a parent path does not call watchers of nested fields. Set cascadeUpdates: true to change that:

{
  "person": {
    "name": ""
  },
  "name": ""
}
import { Button, Code, Stack, TextInput } from '@mantine/core';
import { createFormContext } from '@mantine/form';
import { useState } from 'react';

const [Provider, usePersonFormContext, usePersonForm] = createFormContext<{ person: { name: string } }>();

function Demo() {
  const form = usePersonForm({
    cascadeUpdates: true,
    initialValues: {
      person: { name: "" }
    }
  })

  return (
    <Provider form={form}>
      <Stack>
        <TextInput
          label="Name"
          placeholder="Name"
          {...form.getInputProps('person.name')}
        />
        <Button onClick={() => form.setFieldValue("person", { name: "Jane Doe" })}>Set 'person' object to `{'{ name: "Jane Doe" }'}`</Button>
        <Watcher />
      </Stack>
    </Provider>
  );
}

function Watcher() {
  const form = usePersonFormContext();

  const [person, setPerson] = useState(() => form.getValues().person);
  const [name, setName] = useState(() => form.getValues().person.name);

  form.watch('person', ({ value }) => setPerson(value));
  form.watch("person.name", ({ value }) => setName(value));

  return <Code block>{JSON.stringify({ person, name }, null, 2)}</Code>
}

onValuesChange

The onValuesChange function is called with new and previous values every time form values change. Use it instead of useEffect to subscribe to form value changes:

import { TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';

function Demo() {
  const form = useForm({
    initialValues: {
      name: '',
      email: '',
    },
    onValuesChange: (values) => {
      console.log(values);
    },
  });

  return (
    <div>
      <TextInput
        label="Name"
        placeholder="Name"
        {...form.getInputProps('name')}
      />
      <TextInput
        mt="md"
        label="Email"
        placeholder="Email"
        {...form.getInputProps('email')}
      />
    </div>
  );
}