FormIntermediateSSR-safehooks/forms/useField.ts

useField

Single field state machine.

Import

TypeScript
import { useField } from '@/hooks';

API

Signature

useField({ initialValue, validate? }) → field API

When to use

Use useField instead of re-implementing the same pattern in multiple components.

SSR / Next.js

SSR-safe state machines.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useField
Editor
function EmailField() {
  const email = useField({
    initialValue: '',
    validate: (v) => (!v.includes('@') ? 'Invalid' : undefined),
  });
  return (
    <>
      <input value={email.value} onChange={email.onChange} onBlur={email.onBlur} />
      {email.touched && email.error}
    </>
  );
}
Preview

Implementation source

Full library source for useField — copy into your project when you are not installing a package yet.

hooks/forms/useField.ts
import { useCallback, useState } from 'react';

export interface UseFieldOptions<T> {
  initialValue: T;
  validate?: (value: T) => string | undefined | Promise<string | undefined>;
}

export interface UseFieldReturn<T> {
  value: T;
  error: string | undefined;
  touched: boolean;
  dirty: boolean;
  setValue: (value: T | ((prev: T) => T)) => void;
  onChange: (
    event: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => void;
  onBlur: () => void;
  reset: () => void;
  validate: () => Promise<string | undefined>;
}

/** Single form field state machine. */
export function useField<T>(options: UseFieldOptions<T>): UseFieldReturn<T> {
  const { initialValue, validate } = options;
  const [value, setValue] = useState(initialValue);
  const [error, setError] = useState<string | undefined>(undefined);
  const [touched, setTouched] = useState(false);
  const dirty = !Object.is(value, initialValue);

  const runValidate = useCallback(
    async (next: T) => {
      if (!validate) {
        setError(undefined);
        return undefined;
      }
      const result = await validate(next);
      setError(result);
      return result;
    },
    [validate],
  );

  const onChange = useCallback(
    (
      event: React.ChangeEvent<
        HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
      >,
    ) => {
      const target = event.target;
      let next: unknown = target.value;
      if (target instanceof HTMLInputElement) {
        if (target.type === 'checkbox') next = target.checked;
        else if (target.type === 'number') {
          next = target.value === '' ? '' : target.valueAsNumber;
        }
      }
      setValue(next as T);
      void runValidate(next as T);
    },
    [runValidate],
  );

  const onBlur = useCallback(() => {
    setTouched(true);
    void runValidate(value);
  }, [runValidate, value]);

  const reset = useCallback(() => {
    setValue(initialValue);
    setError(undefined);
    setTouched(false);
  }, [initialValue]);

  return {
    value,
    error,
    touched,
    dirty,
    setValue,
    onChange,
    onBlur,
    reset,
    validate: () => runValidate(value),
  };
}

Copy-paste example

useField.example.tsx
'use client';

import { useField } from '@/hooks';

export function EmailField() {
  const email = useField({
    initialValue: '',
    validate: (v) => (!v.includes('@') ? 'Invalid' : undefined),
  });
  return (
    <>
      <input value={email.value} onChange={email.onChange} onBlur={email.onBlur} />
      {email.touched && email.error}
    </>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Field name attributes must match keys in initialValues for handleChange.
  • Source of truth: open hooks/forms/useField.ts for implementation details