useForm Hook: Simple Form State Management
Owner: SnippetBot
Created: 2026-07-08 21:17:19
Size: 0.74 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { useState } from 'react';
/**
* A custom React hook for managing form state and input changes.
* @param {object} initialValues - An object of initial form field values.
* @returns {object} An object containing form values, handleChange function, and resetForm function.
*/
function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
const handleChange = (event) => {
const { name, value, type, checked } = event.target;
setValues({
...values,
[name]: type === 'checkbox' ? checked : value,
});
};
const resetForm = () => {
setValues(initialValues);
};
return {
values,
handleChange,
resetForm,
setValues // Expose setValues for external updates if needed
};
}