React was written by Facebook and Instagram developers who had learned from the mistakes of their earlier projects on writing JavaScript code for browser-based apps. React’s goal was to solve the problem of developing large applications with different components that needed to have consistent ways of behaving when they interacted with each other, without sacrificing performance and scalability.
React also solves the problem of cross-browser compatibility, where browsers can behave very differently from one.
React become very easy for developers since it introduced react hooks. Most people use react useState() hook to get form data but is it really a good practice? We are going to find the answer today.
When we update a value of a variable with useState(), react re-render the component. Imagine we have 20 form fields and when the user inputs something, we update variables/objects using useState() hook, which means react will keep re-rendering the component until the user stops inputting. This might cause some performance issues.
//useState() example
const [name, setName] = useState(null);
//Form Input
<input name="name" type="text" onChange = {(e) => setName(e.target.value)}/>
So what is the best practice to get form data? The simple answer is to use React useRef() hook. By using the useRef() hook you won’t need to create variable or object for each form fields. Let’s see how we can use useRef() to get form data. Later we will also see how we can validate the form data.
READ : useRef() documentation
Using useRef() hook to get form data in react :
//First import useRef
import { useRef } from "react";
//Create a component
const Form = () => {
//Define useRef() to access form data
const formData = useRef();
//OnSubmit function
const onSubmit = (event) => {
//Disable default action of form submit button
event.preventDefault();
//Accessing form reference with formData variable.
//Object destructuring to get form fields with their name.
const {name, email} = formData.current;
//prining form data in console.
console.log(`Name : ${name.value}, Email : ${email.value}`);
}
//Don't forget to give name prop to each form fields.
return(
<form ref={formData}>
<input type="text" name="name" />
<input type="email" name="email" />
<button type="submit" onClick={onSubmit}>Submit</button>
</form>
);
}
Function for validation :
Now we have learned how we can use react useRef() hook to get form data. Let’s see how we can validate the form data.
//Create a function for validation if a field is empty or not.
//arr parameter is for the names of the fields.
//form parameter is to get form reference.
//This function is good if you have a
//more than 3 form fields.
const isEmpty = (arr, form) => {
//running loop to check
//if a field is empty in form or not.
//if any field is empty return true
//else return false.
for(const key of arr){
if(form[key].value == ""){
return true;
}
}
return false;
}
This is how you will use this function in your component to validate form data.
if(isEmpty(['name', 'email'], formData.current)){
console.log("Something is empty !");
}
else{
console.log("Nothing is empty !");
}
So our final code will look like this.
//First import useRef
import { useRef } from "react";
//Create a component
const Form = () => {
//validation function
const isEmpty = (arr, form) => {
for(const key of arr){
if(form[key].value == ""){
return true;
}
}
return false;
}
//Define useRef() to access form data
const formData = useRef();
//OnSubmit function
const onSubmit = (event) => {
//Disable default action of form submit button
event.preventDefault();
//Accessing form reference with formData variable.
//Object destructuring to get form fields with their name.
const {name, email} = formData.current;
//validating
if(isEmpty(['name', 'email'], formData.current)){
console.log("Something is empty !");
}
else{
//prining form data in console.
console.log(`Name : ${name.value}, Email : ${email.value}`);
}
}
//Don't forget to give name prop to each form fields.
return(
<form ref={formData}>
<input type="text" name="name" />
<input type="email" name="email" />
<button type="submit" onClick={onSubmit}>Submit</button>
</form>
);
}
This is how you can get form data in react without using useState() hook. If you have any questions feel free to comment below I will be happy to answer.