useRef vs event.target.name.value

useRef vs event.target.name.value

·

2 min read

What is the benefit of using useRef, instead of accessing the value "directly"?

For example, the formSubmitHandler function could be implemented like this, which looks simpler to me:

function formSubmitHandler(event) {
  event.preventDefault();
  const enteredName = event.target.name.value;
  // event.target is the form itself, then we access input field with the id "name", and finally its value

  console.log(enteredName);
}

If we had many input fields, they would all have different id, so they would be accessed with, for example

const fName = event.target.fName.value;
const lName = event.target.lName.value;

// etc.

Also, to reset the form, we could then use

event.target.reset();

Is this ok, or is there a reason why useRef would be best practice?

Reply:

Is this ok, or is there a reason why useRef would be best practice?

event.target.value does not give you that persistence that you might need in your application. With refs, you make sure that your values that are defined using refs persists across re-renders. The same is not true for directly accessing the value of an element from DOM using these events. If the input fields do not have a state or a ref managing them, then these values that these fields hold cannot persist across re-renders. This is the reason why using refs or state over the way that we have normally seen is recommended.

Thanks :)