Skip to content

useInputState

useInputState is a React hook that manages an input state with optional value transformation. The returned onChange handler works with both <input> and <textarea> elements.

Interface

ts
function useInputState(
  initialValue: string = '',
  transformValue: (value: string) => string = (v: string) => v
): [
  value: string,
  onChange: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>,
];

Parameters

  • initialValuestring

    The initial value of the input. Defaults to an empty string ("").

  • transformValue(value: string) => string

    A function to transform the input value. Defaults to an identity function that returns the input unchanged.

Return Value

  • [value: string, onChange: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>]

    tuple containing:

    • valuestring

      The current state value.

    • onChangeChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>

      A function to update the state.

Example

tsx
function Example() {
  const [value, onChange] = useInputState('');
  return (
    <>
      <input type="text" value={value} onChange={onChange} />
      <textarea value={value} onChange={onChange} />
    </>
  );
}

Released under the MIT License.