useInputControl

Phillmont MuktarAI Engineer
Languages

Implement a useInputControl hook that manages a controlled input value and tracks additional form input states like:

PropertyTracksWhen it becomes trueWhen it becomes false
TouchedIf input has been focused then blurredWhen the user blurs the input (focus -> blur)Never resets automatically
DirtyIf the value has changed at least onceWhen the user types somethingNever resets automatically
DifferentIf value is different from the originalWhen the value is different from the initialWhen the value is same as the initial

The handleX functions returned by the hook are meant to be called on the relevant event handlers of <input> in order for the hook to work as intended.

export default function Component() {
const nameInput = useInputControl('Oliver');
return (
<form>
<div>
<label htmlFor="name">Name</label>
<input
id="name"
value={nameInput.value}
onChange={nameInput.handleChange}
onBlur={nameInput.handleBlur}
/>
</div>
<p>Touched: {nameInput.touched.toString()}</p>
<p>Dirty: {nameInput.dirty.toString()}</p>
<p>Different: {nameInput.different.toString()}</p>
<button type="submit" disabled={!nameInput.different}>
Submit
</button>
<button type="button" onClick={nameInput.reset}>
Reset
</button>
</form>
);
}

Arguments

  • initialValue: string: The initial value of the input

Returns

The hook returns an object with the following properties:

  • value: string: The current value of the input
  • dirty: boolean: Whether the input value has been modified at least once
  • touched: boolean: Whether the input was focused and blurred
  • different: boolean: Whether the value is different from the initial value
  • handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void: A function that updates the value of the input
  • handleBlur: () => void: A function that should be called when the input is blurred
  • reset: () => void: A function that resets the input value and all derived flags back to their initial state

Loading editor