Controlled & Uncontrolled Components in React

Controlled Components

import { useState } from "react"; 
const ControlledInput = () => {
  const [userName, setUserName] = useState("");
  const onUserNameChanged = (e) => {
    setUserName(e.target.value);
  };

  return (
    <div>
      <div>User name : {userName}</div>
      <input name="user-name" value={userName} onChange={onUserNameChanged} />
    </div>
  );
};

Uncontrolled Components

import { useRef } from "react"; 
const UncontrolledInput = () => {
  const inputValueRef = useRef("");
  const buttonClicked = () => {
    alert(inputValueRef.current.value);
  };
  return (
    <div className="App">
      <input type="text" ref={inputValueRef} />
      <button onClick={buttonClicked}> Submit </button>
    </div>
  );
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store