React form handling

React form handling

If we talking about form handling in react js there are two way handling forms, contrlled and uncontrolled components. Before read this blog if you do not have any information about useState and useRef i recommend that read about them.

Controlled component

As the name says, in the controlled component the form input element’s values and mutations are handle moment by moment. Lets see controlled component form dates life sycle.

oie_VMnsC9XyBaJa.png

Lets see how controlled components work:

import React, { useState } from "react";

const Controlled = () => {
  const [name, setName] = useState("");
  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Name is : ${name}`);
  };

  return (
    <div>
      <form action="" onSubmit={handleSubmit}>
        <input
          type={"text"}
          value={name}
          onChange={(e) => {
            setName(e.target.value);
          }}
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

As you see in the example above we contain form data in state on every change. This is an advantage to easly manuplate state synchronously. But there is one problem about controlled component that becaus of the changing state moment by moment component re rendered much more.

Uncontrolled component

In uncontrolled components we dont controll state moment by moment but how can we handle the data. UseRef helps us. Lets see lyfesycle of uncontrolled component and explain how it works.

oie_g4M5mE1Viqg7.png

Before explanation lets see an example.

Example

import React, { useRef } from "react";

const Uncontrolled = () => {
  const nameRef = useRef(null);
  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Name is : ${nameRef.current.value}`);
  };

  return (
    <div>
      <form action="" onSubmit={handleSubmit}>
        <input ref={nameRef} type={"text"} />
      </form>
    </div>
  );
};

As you see in the example we dont control input state moment by moment, when form submitted we can reach the value of input with property useRef hook ref.current.value.

In the examples i show how use controlled and uncontrolled components. I think there is one big question in your mind when and why i use controlled or uncontrolled components. Let me answer that. If you handle file or simple forms you can use uncontrolled component but if you have to handle complex satate you must use controlled components. I wish it will be usefull.