Install

npm
npm i use-any-hook

Description

The useForm hook simplifies the management of form state in React applications. It provides an easy way to handle form input changes, reset the form, and access the current form values. This hook is particularly useful in scenarios where you need to manage complex forms with multiple fields, offering a clean and reusable solution.

Parameters

NameTypeDescription
initialValuesobjectAn object representing the initial values of the form fields. Each key corresponds to a form field name.

Return Values

NameTypeDescription
valuesobjectThe current state of the form values. Each key corresponds to a form field name and holds the current value.
handleChange(event) => voidA function to handle input changes and update the form state accordingly.
resetForm() => voidA function to reset the form values to their initial state.

Example

useForm.example.tsx
import { useForm } from "use-any-hook";

function MyComponent() {
  const { values, handleChange, resetForm } = useForm({
    username: "",
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    // Use the form values for submission
    console.log("Submitted data:", values);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="username"
        value={values.username}
        onChange={handleChange}
        placeholder="Username"
      />

      <button type="submit">Submit</button>
      <button type="button" onClick={resetForm}>
        Reset
      </button>
    </form>
  );
}