JAVASCRIPT

Simple Controlled Input State Management

Develop a `useInput` React hook for managing the state and change handlers of basic form input fields, streamlining common form interactions.

import { useState } from 'react';

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

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

  return {
    value,
    onChange: handleChange,
    setValue // Optionally expose setValue for programmatic updates
  };
}

export default useInput;

// Example Usage:
// function MyForm() {
//   const firstName = useInput('');
//   const lastName = useInput('');
//
//   const handleSubmit = (e) => {
//     e.preventDefault();
//     console.log('Submitted:', { firstName: firstName.value, lastName: lastName.value });
//     firstName.setValue(''); // Clear input after submission
//     lastName.setValue('');
//   };
//
//   return (
//     <form onSubmit={handleSubmit}>
//       <label>
//         First Name:
//         <input type="text" {...firstName} />
//       </label>
//       <label>
//         Last Name:
//         <input type="text" {...lastName} />
//       </label>
//       <button type="submit">Submit</button>
//     </form>
//   );
// }
How it works: The `useInput` hook provides a concise way to manage the state of controlled input elements in React. It takes an `initialValue` and returns an object containing the current `value`, an `onChange` handler that updates the value, and optionally `setValue` for direct programmatic updates. This simplifies the boilerplate code often associated with managing form inputs, making forms cleaner and easier to develop for basic use cases.

Need help integrating this into your project?

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

Hire DigitalCodeLabs