I joined a Frontend bootcamp and now I have to create a registration form as a part of my first project. I want to use the best practices to be... you know... one of the best students to get hired afterwards.
The registration form has 9 fields including selcet, textareas and usual inputs. And AFAIK every key press inside any of the inputs will cause the whole component rerender because it will change the state of the component. And I think it's not good in terms of performance.
I'm new to React but I think it would be better if I use useRef on textareas and inputs so I won't change the state on every key press. Textareas expect large amount of text in it. So typing for example 400 symbols will cause 400 rerenders. If I need any input data validation or warning (I don't need any for this project actually) I can use the blur event or form submit event.
And then I want to send the form data on "submit" button click.
So is it a good idea? Isn't using so many (9) refs a bad practice? Also is it a good idea to mix useState data (for select, for example) with useRef data (for textareas) to create one form data object? Or it's better to use only one of the hook (either useRef or useState for all form fields)?
P.S. I can't use useMemo because we haven't learn it yet on the bootcamp. Only useState and useRef.
CodePudding user response:
You can use ref together with a formData.
const handleSubmit = (event) => {
event.preventDefault()
const form = new FormData(formRef.current)
const formFields = Object.fromEntries(form)
Object.entries(formFields).forEach(([fieldName, value]) => // do something
// get the value of email input field
form.get('email')
}
<form ref={formRef} onSubmit={handleSubmit}>
<input type="text" name="email" />
<button type="submit">Submit</submit>
</form>
This way you don't need to update the state every time when onChange fires. Read more about formData here: https://developer.mozilla.org/en-US/docs/Web/API/FormData