← Back to all snippets
JAVASCRIPT

Reusable Form Input Management with Custom `useFormInput` Hook

Simplify form state management in React by creating a custom `useFormInput` hook to handle input values and change events across multiple fields.

import React, { useState } from 'react';

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  const reset = () => {
    setValue(initialValue);
  };

  return {
    value,
    onChange: handleChange,
    reset
  };
}

// Example Usage:
// function MyForm() {
//   const firstName = useFormInput('');
//   const lastName = useFormInput('');

//   const handleSubmit = (e) => {
//     e.preventDefault();
//     console.log('Submitted:', { firstName: firstName.value, lastName: lastName.value });
//     firstName.reset();
//     lastName.reset();
//   };

//   return (
//     <form onSubmit={handleSubmit}>
//       <label>
//         First Name:
//         <input type="text" {...firstName} />
//       </label>
//       <br />
//       <label>
//         Last Name:
//         <input type="text" {...lastName} />
//       </label>
//       <br />
//       <button type="submit">Submit</button>
//     </form>
//   );
// }
How it works: The `useFormInput` custom hook provides a streamlined way to manage the state and event handlers for individual form inputs. It encapsulates the `useState` logic for a value and returns an object containing the `value`, an `onChange` handler that updates the state, and a `reset` function to revert to the initial value. This makes form development cleaner and reduces boilerplate code when dealing with multiple input fields.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs