DEV Community

Discussion on: Handling Forms in ReactJS the right way

Collapse
dikamilo profile image
dikamilo • Edited on

Is better to use prevState argument when chaning state based of previous state because setState is asynchronous and may cause unstable updates.

setFormData((prevState) => {
    return {
        ...prevState,
        [e.target.name]: e.target.value
    }
});
Enter fullscreen mode Exit fullscreen mode

or in more short form:

const handleChange = event => 
    setFormData(prevState => 
        ({ ...prevState, [event.target.name]: event.target.value })
    );
Enter fullscreen mode Exit fullscreen mode
Collapse
fazer1929 profile image
Abhishek Agrawal Author

Thank you for the suggestion.