JAVASCRIPT

Manage Single Form Input State with a Custom React Hook

A straightforward React hook for managing the state and change handling of a single form input field, simplifying form development.

import { useState } from 'react';

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

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

  return {
    value,
    onChange: handleChange,
  };
}

export default useFormInput;

// Example Usage:
// function MyForm() {
//   const username = useFormInput('');
//   const email = useFormInput('');
//
//   const handleSubmit = (e) => {
//     e.preventDefault();
//     console.log('Username:', username.value);
//     console.log('Email:', email.value);
//   };
//
//   return (
//     <form onSubmit={handleSubmit}>
//       <input type="text" placeholder="Username" {...username} />
//       <input type="email" placeholder="Email" {...email} />
//       <button type="submit">Submit</button>
//     </form>
//   );
// }
How it works: The `useFormInput` hook is designed to simplify the management of individual form input fields. It encapsulates the `useState` logic for an input's value and provides a `handleChange` function that can be directly spread onto an input element, making it easy to create controlled components. This hook is ideal for simple forms or when you need granular control over each input's state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs