TS
import { useState } from 'react';export default function useForm(defaults) {const [values, setValues] = useState(defaults);const updateValueManually = (name, value) => {setValues({...values,[name]: value,});};const removeValues = () => {setValues(defaults)}function updateValue(e) {// check if its a number and convertlet { value } = e.target;if (e.target.type === 'number') {value = parseInt(e.target.value);}setValues({// copy the existing values into it...values,// update the new value that changed[e.target.name]: value,});}return { values, updateValue, updateValueManually };}
useForm
This is a hook I stole from Wes Bos, with a few extensions of my own
How to use
TS
const {values: { name, email, message },updateValue,updateValueManually,removeValues} = useForm({ name: "", email: "", message: "" });