DEV Community

Cover image for Handle React forms like a pro
Melbite blogging Platform
Melbite blogging Platform

Posted on

2 1 1 1

Handle React forms like a pro

Handling forms data, updates, and form reset in react can be hectic, especially in situations where the form has multiple input fields.

I made a 1-minute video on best practices in handling forms data in ReactJs

Was this tips helpful? What other ReactJs tips would you advise in react forms? Leave a comment below.

Thank you

Top comments (3)

Collapse
 
brense profile image
Rense Bakker β€’

I would advise to not use controlled inputs at all. You can access named input values inside the form element onChange (if you want to do validation) and onSubmit handler (if you want to submit the form data).

Collapse
 
cookiemonsterdev profile image
Mykhailo Toporkov πŸ‡ΊπŸ‡¦ β€’ β€’ Edited

In general for complex forms, it is better to use some specialized libs like react-hook-form or formik cause they provide more options for error handling and validation. But even so, instead many useState hooks better use only one with object sth like:

const [formData, setFormData] = useState({
    name: "",
    email: "",
})

<form>
    <Input id="name" value={formData.name}  onChange={e => setFormData(prev => ({...prev, name: e.target.value})} />
    <Input id="email" value={formData.name}  onChange={e => setFormData(prev => ({...prev, email: e.target.value})} />
</form>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ninacnel profile image
Nerina β€’

Handling forms' inputs with useState would cause a lot of renders of the component, isn't it better way to handle forms with useRef? Saludos!

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more