Rooks
HooksKeyboard & Input

useInput

Returns controlled input value and change props with optional validation.

About

useInput manages the value and onChange props for one controlled HTML input. An optional validator can reject a proposed value before state changes.

Example

import { useInput } from "rooks";

export default function ShortNameInput() {
  const name = useInput("", {
    validate: (nextValue) => nextValue.length <= 12,
  });

  return (
    <label>
      Short name
      <input {...name} />
      <span>{name.value.length}/12 characters</span>
    </label>
  );
}

Parameters

  • initialValue: number | string | readonly string[] | undefined; defaults to "".
  • options.validate(nextValue, currentValue): optional predicate. Returning false rejects the change; returning true accepts it.

The private options shape is shown inline and is not an importable package type.

Return value

The hook returns { value, onChange }, ready to spread onto an <input>. The change handler receives a React input change event.

Behavior and lifecycle

The handler reads event.target.value, which is a string at runtime, and casts it to the selected generic type. A numeric initial value therefore does not parse later text into a number. Validator exceptions are not caught and propagate from the change handler. When initialValue changes, an effect resets the managed value to it, overwriting intervening user input after that render.

Compatibility and accessibility

The hook uses React state and effects and is safe during server rendering. It does not supply a label, input type, parsing, error message, or ARIA attributes; the consuming form must provide them.

On this page