DEV Community

Discussion on: How To Simplify React Forms State Handlers

Collapse
 
griffinfoster profile image
Griffin Foster • Edited

Great post! Super informative and a great option for form state handling. If your goal is to improve readability and minimize code length, have you considered using a single state object with all fields stored within it. You would then use a single value change handler that would look like:

const onChange = (e) => setState({...state, [e.target.name]: e.target.value})

This function would eliminate the need for multiple lines of useState as well as a custom Hook, and instead cover all form fields in one line.
Just a thought, hope this is helpful and have a great day!

Collapse
 
arjayosma profile image
Arjay

This is awesome! I haven't looked much into this setup but this can be a great addition.
I'll experiment with this one and update this post and my blog if it works.

If I'm not mistaken, this is the hook equivalent to the implementation of pre-hook state handling of user input.

But the way I am seeing it is we're spreading the state and updating the entire state object, which I'm sure will definitely work. This can be a great addition to minimize and simplify codes.

I just wanted to point out, though I might have missed it, that the purpose of the examples I provided above was for extensibility and reusability in case we want to add functionality to the way we handle our forms. :D