简体   繁体   中英

What is the best way to use states in react for input variables?

I am fairly new to react I have an input form in React Typescript and I want to use the useState hook for storing the values of name, email, and other input tags. I am using state like this:

type Props = {
    name: string,
    email: string,
    message: string,
}

const ContactMe = () => {
    const [formInputs, setFormInputs] = useState<Props>({
        name: '',
        email: '',
        message: '',
    });
    const handleData = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
    }

Is it the right approach like this or should I need to have a separate state for each input element?

Is it the right approach like this or should I need to have a separate state for each input element?

You could use separate state for each input element for small form, and object for a larger form.

As you need to clone object while set new value like this way:

setFormInputs({
    ... formInputs,
    name: 'newName'
})

it may cause performance issue in a big form, I suggest to use react-hook-form for better performance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM