Now, how do you decide which one to use? It depends what you plan to do with the entered value.
If you are only interested in it once when the form is submitted, a ref might be better because logging and updating the state value with every keystroke is a bit overkill then.
You don't need to do that if you only want the value once. However, if you of course need the value, the entered value after every keystroke, for example, for instant validation, then using the state is better because with a ref you can't really do that. Another reason for using a state instead of a ref could be, if you want to reset the entered input. Let's say here at the end of the form submission handler. There we can reset the entered name by calling set entered name and setting this to an empty string. And all we now need to do is bind the entered value back to the input through the value prop.
import React, { useRef, useState } from 'react'
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = event => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredValue = nameInputRef.current.value;
console.log(enteredValue);
//nameInputRef.current.value = ''; => not ideal , Dont Dont
//Manipulate the DOM
setEnteredName('');
}
return (
<form onSubmit={formSubmissionHandler}>
<div className='form-control'>
<label htmlFor='name'>Your Name</label>
<input ref={nameInputRef} value={enteredName} type='text' id='name' onChange={nameInputChangeHandler} />
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
Note: We use useRef to reset a input in the form it works but it's not ideal because we are directly manipulating the dom here, we're using some vanilla JavaScript code to directly reach out to the dom and change something there. And that is typically not something you should do. we should leave that up to react. React should be the only thing manipulating the dom. And therefore this is not ideal, don't manipulate the dom.
The entered name is now bound to the value prop on input. And hence, if we update the entered name, that will be reflected here. This works great when using state, but it's not really possible with refs, at least not as elegant.
With refs, you could also use your ref and access the input element which is stored in that ref, and set value equal to an empty string. But this is not an ideal way of doing it. It works, if I comment out this, it works as you can tell, but it's not ideal because we are directly manipulating the dom here, we're using some vanilla JavaScript code to directly reach out to the dom and change something there. And that is typically not something you should do. You should leave that up to react.
React should be the only thing manipulating the dom. And therefore this is not ideal, don't manipulate the dom.