Skip to content

Form Management Hook

Medium ~40 min

What you'll build

A useForm hook that manages field values, tracks touched/dirty state, runs validators, and returns props for controlled inputs.

Goals

  • Manage form field state in a single object
  • Track touched and dirty fields
  • Run validators and collect errors
  • Generate props for controlled inputs

Prerequisites

  • useState and custom hooks
  • Controlled inputs in React
  • Object spread and computed keys

Steps

  1. 1

    Set up the hook state

    Create useForm(initialValues) that holds values, errors, and touched state. Return handleChange, handleBlur, handleSubmit, and the current state.

    Code
    function useForm(initialValues) {
      const [values, setValues] = useState(initialValues);
      const [errors, setErrors] = useState({});
      const [touched, setTouched] = useState({});
      return { values, errors, touched };
    }

    Expected result

    The hook returns the initial state with empty errors and touched.

  2. 2

    Implement handleChange

    handleChange takes an event and updates values[field] using computed property keys. This works for any input with a name attribute.

    Code
    const handleChange = (e) => {
      const { name, value } = e.target;
      setValues(prev => ({ ...prev, [name]: value }));
    };

    Expected result

    Typing in a field updates values[fieldName].

  3. 3

    Add validation

    Accept a validate function that takes values and returns an errors object. Run it on change or blur, depending on your UX preference.

  4. 4

    Implement handleSubmit

    handleSubmit takes an onSubmit callback, prevents default, runs final validation, and only calls onSubmit if there are no errors.

  5. 5

    Build a registration form

    Use useForm to build a registration form with name, email, and password. Add a validate function that checks required fields and email format.

    Code
    function RegistrationForm() {
      const { values, errors, handleChange, handleSubmit } = useForm(
        { name: '', email: '', password: '' },
        (vals) => {
          const errs = {};
          if (!vals.name) errs.name = 'Required';
          if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(vals.email)) errs.email = 'Invalid email';
          if (vals.password.length < 8) errs.password = 'Too short';
          return errs;
        }
      );
      
      return (
        <form onSubmit={handleSubmit(data => console.log('Submitted:', data))}>
          <input name="name" value={values.name} onChange={handleChange} />
          {errors.name && <span>{errors.name}</span>}
          {/* email, password similarly */}
          <button type="submit">Register</button>
        </form>
      );
    }

    Expected result

    Form shows errors on invalid input and logs data on valid submit.

Try it yourself

What you learned

You built a form management hook — the core of libraries like react-hook-form. Understanding this helps you choose or build the right form solution.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic