Usage: useState or useRef in form submit

Viewed 2358

Normally when I handle form submits, I use useState for input values and set onChange event as

const [inputValues, setInputValues] = useState({
    title: "",
    address: "init"
  });

  function submitHandler(e) {
    e.preventDefault();

    const meetupData = {
      meetupTitle: inputValues.title,
    };

    console.log(meetupData);
  }
  return (
    <form onSubmit={submitHandler}>
      <div>
        <label htmlFor="title">Meetup Title</label>
        <input
          type="text"
          required
          id="title"
          value={inputValues.title}
          onChange={(e) =>
            setInputValues({ ...inputValues, title: e.target.value })
          }
        />
      </div>
      <div>
        <button>Add Meetup</button>
      </div>
    </form>
  );

but in some tutorial I found out it's written using useRef as

const titleInputRef = useRef();

  function submitHandler(e) {
    e.preventDefault();
    const enteredTitle = titleInputRef.current.value;

    const meetupData = {
      title: enteredTitle,
    };

    console.log(meetupData);
  }
  return (
    <form onSubmit={submitHandler}>
      <div>
        <label htmlFor="title">Meetup Title</label>
        <input type="text" required id="title" ref={titleInputRef} />
      </div>
      <div>
        <button>Add Meetup</button>
      </div>
    </form>
  );

and I am trying to understand what's the difference and which one could be better in general performance ?

2 Answers

There are pros and cons.

  • If you you keep form values in state (aka controlled components) one benefit is you can for example immediately access values on change, for example if you want to have some button disabled in case user types something in the input box.
  • If you take ref approach (aka uncontrolled components) one benefit is that you don't have to re render your component each time user types (because calling state update does a re render).

AFAIK react recommends controlled components, but uncontrolled ones are an alternative too.

By purpose, if you use useState, you get both a getter and a setter(which triggers rerender to update the value immediately), while if you use useRef you only get a getter.

Hence, if you use useRef, you do not need to set value={state}, while useState does.

In general, if you want to validate values input from user (e.g. with onChange event) you have to use useState, if you only want to get the value on submission of the form, you are free to use useRef.

Related